package com.hp.bon.sgw.wh.channel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hp.bon.omc.util.StringUtil;
import com.hp.bon.sgw.Constants.NodeStatus;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.IChannel;
import com.hp.bon.sgw.domain.Node;
import com.hp.bon.sgw.domain.SGWChannel;
import com.hp.bon.sgw.service.ConfigListener;
import com.hp.bon.sgw.service.ConfigService;
import com.hp.bon.sgw.start.SpringContext;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.wh.Constants.AliParam;
import com.hp.bon.sgw.wh.bean.InvoiceInformation;
import com.hp.bon.sgw.wh.bean.MonthlyBillError;
import com.hp.bon.sgw.wh.bean.tmall.*;
import com.hp.bon.sgw.wh.channel.common.BizConsts;
import com.hp.bon.sgw.wh.channel.handler.*;
import com.hp.bon.sgw.wh.channel.invoices.InvoiceBizProcedure;
import com.hp.bon.sgw.wh.service.TMallResponseService;
import com.hp.bon.sgw.wh.service.UserResourceConfigService;
import com.hp.bon.sgw.wh.service.WHConfigService;
import com.hp.bon.sgw.wh.utils.*;
import com.hp.ocs.diameter.DiameterUtils;
import net.sf.json.JSONObject;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.simpleframework.http.Query;
import org.simpleframework.http.Request;
import org.simpleframework.http.Response;
import org.simpleframework.http.core.Container;
import org.simpleframework.http.core.ContainerProcessor;
import org.simpleframework.http.core.ContainerSelector;
import org.simpleframework.http.core.ContainerServer;
import org.simpleframework.transport.connect.Connection;
import org.simpleframework.transport.connect.SocketConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * @ClassName: TMallChannel
 * @author: wanghan
 * @date:2016年3月14日 上午9:41:10
 * @update : By C.J 
 * @原因:1)需求变动:(湖北)天猫和湖北电信SGW固话宽带充值&查询(2016年上线)接口异步流程优化需求-20171129',调整TaobaoPay\TaobaoQuery接口实现
 *      2)需求变动:(湖北)天猫旗舰店和湖北电信SGW手机直充(2015年上线)接口流程优化需求-20171129.doc,调整tmallPay\tmallPay接口实现
 *      3)代码调整、优化、改造
 * @date 2017年12月4日 上午11:57:06
 */
public class TMallChannel implements Container, ConfigListener, IChannel {

	private static final Logger _log = LoggerFactory
			.getLogger(TMallChannel.class);
	private ContainerServer server = null;
	private SGWChannel channel;
	private ThreadPoolTaskExecutor asynExecutor;
	private MultiThreadedHttpConnectionManager connectionManager;
	private HttpClient httpClient;
	private ThreadPoolExecutor executor;
	private ThreadPoolExecutor collector;
	private static String TmallPay = "tmallPay";
	private static String TmallOrderQuery = "tmallOrderQuery";
	private static String TmallOrderCancel = "tmallOrderCancel";
	static XMLInputFactory inputFactory = XMLInputFactory.newInstance();
	private static String TmallFlux = "tmallFlux";
	private static String TmallFluxQuery = "tmallFluxQuery";

	private static String TaobaoPay = "TaobaoPay";
	private static String MonthlyBill = "monthlyBill";
	private static String PAYMENT = "payment";
	private static String ORDERONEITEM ="orderOneItem";
	public static String INVOICEINFORMATION ="invoiceInformation";
	private static String TaobaoQuery = "TaobaoQuery";
	private static String ISSUEINVOICE = "issueInvoice";
	private static String PointExchange = "PointExchange";
	private static String NetListQuery = "NetListQuery";


    public static String STATUS_UNDERWAY = "UNDERWAY";
    public static String STATUS_SUCCESS = "SUCCESS";
	public static String STATUS_FAIL = "FAILED";
    public static String STATUS_TS_EXPIRED = "TS_EXPIRED";
	public static String REQUEST_FAIL = "REQUEST_FAILED";
	public static String ORDER_NOT_EXIST = "ORDER_NOT_EXISTS";
	public static String ORDER_FAIL = "ORDER_FAILED";
	public static String INVOICE = "invoice";
	public static String INVOICE_HB = "invoice_hb";
	public static String CANCEL = "CANCEL";
	public static String BIZTYPETEMP = "";
	
	public static InvoiceBizProcedure invoiceBizProcedure;
	
	private WHConfigService whConfigService;
	private UserResourceConfigService userResourceConfigService ;
	private ConfigService confSrv;
	private TMallResponseService tmallResponseService;
	private Map<String, Integer> cardIdMap;

	private Map<String, Integer> spuIdMap;
	private Map<String, Integer> spuIdBalanceMap;

	private Map<String, Integer> fluxspuIdMap;
	private Map<String, Integer> fluxpricePlanIdMap;
	private Map<String, Integer> fluxpricePlanIdWHMap;
	private Map<String, Integer> ProductIdMap;
	private Map<String, Integer> AmountMap;
	private String cfgCoopId = "";
	private String tmallRetUrl = "";
	private String pointExchange_url = "";
	private String netListQuery_url = "";
	private String tmallFlow_url = "";
	private String rollbackExchange_url = "";
	private String taobao_supplierId = "";
	private String tmallflux_supplierId = "";
	private String IS_WUHAN = "84201";
	private String IS_WUHAN2 = "1001";
	private String MonthlyBillWUHANURL = "";
	private String MonthlyBillHBURL = "";
	private String MonthlyBillWHjf3 = "";
	private String MonthlyBillHBjf3 = "";
//	private String jf3_latn_id = "";
//	private String jf3_jt_latn_id = "";
//	private String jf3_flag = "";
	private String EopInvoiceURL = "";

	public TMallChannel(SGWChannel channel) {
		this.channel = channel;
		asynExecutor = SpringContext.getApplicationContext().getBean(
				ThreadPoolTaskExecutor.class);
		confSrv = SpringContext.getInstance().getConfigService();
		whConfigService = SpringContext.getApplicationContext().getBean(
				WHConfigService.class);
		tmallResponseService = SpringContext.getApplicationContext().getBean(
				TMallResponseService.class);
		String cardId = whConfigService.getValue("tmall.cardId", "");
		Gson gson = new Gson();
		cardIdMap = gson.fromJson(cardId,
				new TypeToken<Map<String, Integer>>() {
				}.getType());

		cfgCoopId = whConfigService.getValue("tmall.coopId", "");
		tmallRetUrl = whConfigService.getValue("tmall.returl", "");

		String spuId = whConfigService.getValue("taobao.spuId", "");
		spuIdMap = gson.fromJson(spuId, new TypeToken<Map<String, Integer>>() {
		}.getType());

		String spuIdBalance = whConfigService.getValue("taobao.spuIdBalance",
				"");
		spuIdBalanceMap = gson.fromJson(spuIdBalance,
				new TypeToken<Map<String, Integer>>() {
				}.getType());

		String ProductId = whConfigService.getValue("point.ProductId", "");
		ProductIdMap = gson.fromJson(ProductId,
				new TypeToken<Map<String, Integer>>() {
				}.getType());

		String Amount = whConfigService.getValue("point.Amount", "");
		AmountMap = gson.fromJson(Amount,
				new TypeToken<Map<String, Integer>>() {
				}.getType());

		String tmallplux = whConfigService.getValue("tmallflux.spuId", "");
		fluxspuIdMap = gson.fromJson(tmallplux,
				new TypeToken<Map<String, Integer>>() {
				}.getType());

		String pricePlanId = whConfigService.getValue("tmallflux.pricePlanId",
				"");
		fluxpricePlanIdMap = gson.fromJson(pricePlanId,
				new TypeToken<Map<String, Integer>>() {
				}.getType());

		String pricePlanIdWH = whConfigService.getValue(
				"tmallflux.pricePlanIdWH", "");
		fluxpricePlanIdWHMap = gson.fromJson(pricePlanIdWH,
				new TypeToken<Map<String, Integer>>() {
				}.getType());

		pointExchange_url = whConfigService.getValue("pointExchange.url", "");

		netListQuery_url = whConfigService.getValue("netListQuery.url", "");

		rollbackExchange_url = whConfigService.getValue("rollbackExchange.url",
				"");

		tmallFlow_url = whConfigService.getValue("tmallflux.url", "");

		taobao_supplierId = whConfigService.getValue("taobao.supplierId", "");

		tmallflux_supplierId = whConfigService.getValue("tmallflux.supplierId",
				"");
		
		MonthlyBillWUHANURL = whConfigService.getValue("MonthlyBillWH","");
		MonthlyBillHBURL = whConfigService.getValue("MonthlyBillHB","");
		
		MonthlyBillWHjf3 = whConfigService.getValue("MonthlyBillWHjf3","");
		MonthlyBillHBjf3 = whConfigService.getValue("MonthlyBillHBjf3","");
		
		EopInvoiceURL = whConfigService.getValue("EopInvoice","");
	}

	@Override
	public void addPersist(Node arg0) {
	}

	@Override
	public void deletePersist(Node arg0) {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @param arg0
	 * 
	 * @return
	 * 
	 * @see
	 * com.hp.bon.sgw.core.channel.IChannel#getNodeSendQueueSize(java.lang.String
	 * )
	 */
	@Override
	public int getNodeSendQueueSize(String arg0) {
		return 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @return
	 * 
	 * @see com.hp.bon.sgw.core.channel.IChannel#getSGWChannel()
	 */
	@Override
	public SGWChannel getSGWChannel() {
		return this.channel;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @return
	 * 
	 * @see com.hp.bon.sgw.core.channel.IChannel#getThreadPoolActiveCount()
	 */
	@Override
	public int getThreadPoolActiveCount() {
		return 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @return
	 * 
	 * @see com.hp.bon.sgw.core.channel.IChannel#getThreadPoolQueueSize()
	 */
	@Override
	public int getThreadPoolQueueSize() {
		return 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @return
	 * 
	 * @see com.hp.bon.sgw.core.channel.IChannel#getThreadPoolSize()
	 */
	@Override
	public int getThreadPoolSize() {
		return 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @param arg0
	 * 
	 * @return
	 * 
	 * @see
	 * com.hp.bon.sgw.core.channel.IChannel#sendRequest(com.hp.bon.sgw.core.
	 * CallParam)
	 */
	@Override
	public int sendRequest(CallParam arg0) {
		return 0;
	}

	@Override
	public void start() throws IOException {
		_log.info("start TMallChannel:" + channel.toString() + " ...");
		String key = "sgw.tmallchannel.thread.max";
		int maxThreads = confSrv.getIntValue(key, 20);
		String endPoint = this.channel.getUri();
		if (endPoint == null) {
			_log.warn("channel dont't defined uri");
			return;
		}
		_log.info("start sgw TMallChannel server portal at " + endPoint);

		try {
			URL srvURL = new URL(endPoint);
			int port = srvURL.getPort();
			// 找不到端口就启动失败
			if (port == -1) {
				_log.info("start TMallChannel error : port Not defined");
				return;
			}
			String host = srvURL.getHost();
			if (host.equals("127.0.0.1") || host.equalsIgnoreCase("localhost")) {
				host = "0.0.0.0";
			}
			server = new ContainerServer(this, maxThreads);

			Connection connection = new SocketConnection(server);
			SocketAddress address = new InetSocketAddress(host, port);
			connection.connect(address);
			collector = ((ContainerSelector) ((ContainerProcessor) server
					.getProcessor()).getSelector()).getCollect().getQueue();
			executor = ((ContainerSelector) ((ContainerProcessor) server
					.getProcessor()).getSelector()).getExecutor().getQueue();
			connectionManager = new MultiThreadedHttpConnectionManager();
			// ... configure connectionManager ...
			httpClient = new HttpClient(connectionManager);
			httpClient.getHttpConnectionManager().getParams()
					.setConnectionTimeout(10000);
			httpClient.getHttpConnectionManager().getParams()
					.setSoTimeout(45000);
			
			//初始化invoiceBizProcedure: 帐务中心新电子发票接口
			invoiceBizProcedure = InvoiceBizProcedure.instance();

			this.channel.setStatus(NodeStatus.ON_LINE);
			confSrv.updateChannelStatus2DB(this.channel.getId(),
					NodeStatus.ON_LINE);
		} catch (IOException e) {
			e.printStackTrace();
			_log.error("start TMallChannel " + this.channel.toString()
					+ " err " + e);
		}
	}

	@Override
	public void stop() {
		_log.info("stop BlackCard channel");
		if (server != null) {
			try {
				server.stop();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (connectionManager != null) {
			connectionManager.shutdown();
		}

		this.channel.setStatus(NodeStatus.OFF_LINE);
		confSrv.updateChannelStatus2DB(this.channel.getId(),
				NodeStatus.OFF_LINE);

		try {
			_log.info("wait 3s to exit...");
			Thread.sleep(3 * 1000);
		} catch (InterruptedException e) {
			_log.warn("Thread.sleep InterruptedException:", e);
		}
	}

	@Override
	public Set<String> monitorConfKeys() {
		return null;
	}

	@Override
	public void onConfigUpdated(String arg0) {

	}

	private void errorAck(PrintStream body, String tbOrderNo,
			String coopOrderNo, String status, String failedCode,
			String failedReason) {
		try {
			Map<String, String> data = new HashMap<String, String>();
			data.put("tbOrderNo", tbOrderNo);
			data.put("coopOrderNo", coopOrderNo);
			data.put("coopOrderStatus", status);
			data.put("coopOrderSnap", "ReCharge");
			data.put("coopOrderSuccessTime", "");
			data.put("failedCode", failedCode);
			data.put("failedReason", failedReason);
			String response = tmallResponseService.getResponse(data);
			body.write(response.getBytes("GBK"));
			body.close();
		} catch (Exception e) {
			_log.error("TMallChannel errorAck error, msg = {}", e.getMessage());
            _log.error("",e);
		}
	}

	private void errorAck1(PrintStream body, String bizType, String tbOrderNo,
			String coopOrderNo, String status, String failedCode,
			String failedReason) {
		try {

			Map<String, String> data = new HashMap<String, String>();
			data.put("tbOrderNo", tbOrderNo);
			data.put("bizType", bizType);
			data.put("coopOrderNo", coopOrderNo);
			data.put("coopOrderStatus", status);
			data.put("errCode", failedCode);
			data.put("errDesc", failedReason);
            String newCode = ResultCodeUtil.updateResultCode(data.get("errCode"), userResourceConfigService.getValue("taobao_resultCode"), userResourceConfigService.getValue("taobao_defaultResult"));
            data.put("errCode",newCode);
            if(StringUtil.isBlank(failedReason)){
                data.put("errDesc", newCode);
            }
			String response = tmallResponseService.getResponse1(data);
			body.write(response.getBytes("UTF-8"));
			body.close();
		} catch (Exception e) {
			_log.error("TMallChannel errorAck error1, msg = {}", e.getMessage());
            _log.error("",e);
		}
	}

	private void suAck(PrintStream body, String bizType, String tbOrderNo,
			String coopOrderNo, String status, String failedCode,
			String failedReason) {
		try {
			Map<String, String> data = new HashMap<String, String>();
			data.put("tbOrderNo", tbOrderNo);
			data.put("bizType", bizType);
			data.put("coopOrderNo", coopOrderNo);
			data.put("coopOrderStatus", status);
			data.put("errCode", failedCode);
			data.put("errDesc", failedReason);
			String response = tmallResponseService.getResponse1(data);
			body.write(response.getBytes("GBK"));
			body.close();
		} catch (Exception e) {
			_log.error("TMallChannel errorAck error suAck, msg = {}", e.getMessage());
            _log.error("",e);
		}
	}

	private void errorAck2(PrintStream body, String Result, String Result_desc,
			String Acc_Nbr, String Payment_Serial_Nbr, String UsedPoint,
			String CurrMonthPoint) {
		try {
			Map<String, String> data = new HashMap<String, String>();
			data.put("Result", Result);
			data.put("Result_desc", Result_desc);
			data.put("Acc_Nbr", Acc_Nbr);
			data.put("Payment_Serial_Nbr", Payment_Serial_Nbr);
			data.put("UsedPoint", UsedPoint);
			data.put("CurrMonthPoint", CurrMonthPoint);
			String response = tmallResponseService.getResponse2(data);
			body.write(response.getBytes("GBK"));
			body.close();
		} catch (Exception e) {
			_log.error("TMallChannel errorAck error2, msg = {}", e.getMessage());
            _log.error("",e);
		}
	}

	@Override
	public void handle(Request request, Response response) {
        long startTime = System.currentTimeMillis();
        _log.info("TMallChannel receive request from "
				+ request.getClientAddress() + "; " + request.toString());
		String pubKeyValue = whConfigService.getValue(AliParam.tmallPubKeyValue, "");
		String bankCode = whConfigService.getValue(AliParam.tmallBankCode,"ALIBB");
		String requestPath = request.getPath().getPath();
		String IP = request.getClientAddress().getAddress().getHostAddress();
		List<String> headerNames =  request.getNames();
		String value = request.getValue("X-CTG-Request-ID");
		String valueOriginalId = request.getValue("Original-CTG-Request-ID");
		String resultCode="-1";//标识返回码 -1 表示 不需要记录的接口
		//String Jf3_jt_latn_id = request.getValue("Jf3_jt_latn_id");//割接地市配置项（多个地市用逗号分隔，如果配置项调整为888，则表示全部调用新地址）；
		
		_log.info("headerNames-----------"+headerNames.size());
		_log.info("getMathod----"+request.getMethod());
		_log.info("value-----------"+value);
		_log.info("requestPath111"+requestPath);
		_log.info("IP++++"+IP);
		if (!requestPath.endsWith(NetListQuery)) {
			_log.info("query = {}", request.getQuery());
			Query query = request.getQuery();
			for (String s : query.keySet()) {
				_log.info("key = {}", s);
				_log.info("value = {}", query.get(s));
			}
		}
		long receiveTime = System.currentTimeMillis();
		PrintStream body = null;
		try {
			body = response.getPrintStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		response.set("Content-Type", "text/xml;charset=UTF-8");
		response.setDate("Date", receiveTime);
		response.setDate("Last-Modified", receiveTime);
		
		// 检查是否走新流程，并处理新流程，若返回[TYPE_ORIG_FLOW]则表示走老流程
		invoiceBizProcedure.setUserResourceConfigService(userResourceConfigService);
		invoiceBizProcedure.setTMallResponseService(tmallResponseService);
		String retCode = invoiceBizProcedure.doProcedure(request, response, startTime);
		if(!BizConsts.TYPE_ORIG_FLOW.equals(retCode)) {
			_log.info("working on the new flow, and completely.");
			return;
		}
		_log.info("working on the old flow...");
		
		//response.
		try {
			if (requestPath.endsWith(TmallPay)) { 
				// 直冲
				_log.info("start tmallPay......");
				String coopId = request.getParameter("coopId") == null ? ""
						: request.getParameter("coopId");
				String tbOrderNo = request.getParameter("tbOrderNo") == null ? ""
						: request.getParameter("tbOrderNo");
				String cardId = request.getParameter("cardId") == null ? ""
						: request.getParameter("cardId");
				String cardNum = request.getParameter("cardNum") == null ? ""
						: request.getParameter("cardNum");
				String customer = request.getParameter("customer") == null ? ""
						: request.getParameter("customer");
				String sum = request.getParameter("sum") == null ? "" : request
						.getParameter("sum");
				String gameId = request.getParameter("gameId") == null ? ""
						: request.getParameter("gameId");
				String section1 = request.getParameter("section1") == null ? ""
						: request.getParameter("section1");
				String section2 = request.getParameter("section2") == null ? ""
						: request.getParameter("section2");
				String tbOrderSnap = request.getParameter("tbOrderSnap") == null ? "" : new String(request.getParameter("tbOrderSnap").getBytes("UTF-8"), "ISO-8859-1");
				_log.info("tbOrderSnap decode before:{}", tbOrderSnap);
				tbOrderSnap = URLDecoder.decode(tbOrderSnap, "GBK");
				String notifyUrl = request.getParameter("notifyUrl") == null ? "" : request.getParameter("notifyUrl");
				String sign = request.getParameter("sign") == null ? "" : request.getParameter("sign");
				String version = request.getParameter("version") == null ? "" : request.getParameter("version");
				if (coopId.equals("") || tbOrderNo.equals("")
						|| cardId.equals("") || cardNum.equals("")
						|| customer.equals("") || sum.equals("")
						|| tbOrderSnap.equals("") || sign.equals("")
						|| notifyUrl.equals("")) {
					errorAck(body, tbOrderNo, tbOrderNo, REQUEST_FAIL, "0101","");
					return;
				}
				if (cfgCoopId.indexOf(coopId) < 0) {
					_log.warn("coopId:? not in config", coopId);
					errorAck(body, tbOrderNo, tbOrderNo, ORDER_FAIL, "0306", "");
					return;
				}
				int intCardNum = 0;
				try {
					intCardNum = Integer.parseInt(cardNum);
					if (cardIdMap.get(cardId) == null) {
						_log.warn("cardId 在配置文件中未发现，cardId = {}", cardId);
						errorAck(body, tbOrderNo, tbOrderNo, ORDER_FAIL,"0305", "");
						return;
					}
				} catch (Exception e) {
					errorAck(body, tbOrderNo, tbOrderNo, ORDER_FAIL, "0302", "");
				}
				Pattern pattern = Pattern.compile("[0-9]*");
				Matcher matcher = pattern.matcher(customer);
				if (!matcher.matches()) {
					_log.warn("customer is not number, customer = ?", customer);
					errorAck(body, tbOrderNo, tbOrderNo, ORDER_FAIL, "0306", "");
					return;
				}
				TMallPayBean tmallPayBean = new TMallPayBean(coopId, tbOrderNo,
						cardId, cardNum, customer, sum, gameId, section1,
						section2, tbOrderSnap, notifyUrl, sign, version);
				// 验证签名
				_log.info("pubkeyValue = {}", pubKeyValue);
				_log.info("String = {}", tmallPayBean.toString());
				_log.info("tbOrderSnap = {}", tbOrderSnap);
				_log.info("sign = {}", sign);
				/*
				 * String md5Sign = tmallPayBean.toString() + pubKeyValue;
				 * if(!SignUtilsImpl.checkTmallSign(md5Sign,sign)) {
				 * 	   errorAck(body, tbOrderNo, tbOrderNo,REQUEST_FAIL,"0102", "");
				 * 	   return; 
				 * }
				 */
				
				String payment_Amount = intCardNum * cardIdMap.get(cardId) + "";
				String jf3_flag = userResourceConfigService.getValue("jf3_flag","");
				Element serviceInformation = TmallPayUtil.getServiceInfoEle(customer, bankCode, tbOrderNo, payment_Amount, sum,jf3_flag);
				
				_log.info("jf3_flag 鉴定完毕== {}", serviceInformation == null);
				XmlMessage req = new XmlMessage(true);
				String tmallHostId = whConfigService.getValue(AliParam.tmallHostId, "Alibaba1@027.ctnbc-bon.net");
				String sessionId = DiameterUtils.makeSessionID(tmallHostId);
				req.setIp(IP);
				req.setMsgTime(receiveTime);
				req.setMID(sessionId);
				req.setUID(tmallHostId);
				req.setSCID("0".equals(jf3_flag) ? "Recharge.SGW@027.ctnbc-bon.net":"ServAuth.jf3@027.ctnbc-bon.net");
				req.setSIG(null);
				req.setREPTAG(0);
				req.setDATA(serviceInformation.asXML());
				req.setDataElement(serviceInformation);
				JSONObject jsonObject=new JSONObject();
				jsonObject.put("coopId", coopId);
				jsonObject.put("tbOrderNo", tbOrderNo);
				jsonObject.put("cardId", cardId);
				jsonObject.put("cardNum", cardNum);
				jsonObject.put("customer", customer);
				jsonObject.put("sum", sum);
				jsonObject.put("IP", IP);
				jsonObject.put("gameId", gameId);
				jsonObject.put("section1", section1);
				jsonObject.put("section2", section2);
				jsonObject.put("tbOrderSnap", tbOrderSnap);
				jsonObject.put("payment_Amount", payment_Amount);
				jsonObject.put("bankCode", bankCode);
				
//					jsonObject.put("req", req);
				
				_log.info("=======开关==jf3_flag:"+jf3_flag);
				_log.info("=======DCC请求开始==SICD:"+req.getSCID());
				// new CallParam对象
				TMallPayHandle tmallPayHandle = new TMallPayHandle(body,tmallPayBean, tmallResponseService, asynExecutor,tmallRetUrl, pubKeyValue,jsonObject);
				CallParam callParam = new CallParam(req.getMID(),req.getSCID(), req, req.getUID(), tmallPayHandle);
				BuzProcessorManager.getInstance().processRequest(callParam);
//				
//				
//				_log.info("start tmallPay......");
//				String coopId = request.getParameter("coopId") == null ? ""
//						: request.getParameter("coopId");
//				String tbOrderNo = request.getParameter("tbOrderNo") == null ? ""
//						: request.getParameter("tbOrderNo");
//				String cardId = request.getParameter("cardId") == null ? ""
//						: request.getParameter("cardId");
//				String cardNum = request.getParameter("cardNum") == null ? ""
//						: request.getParameter("cardNum");
//				String customer = request.getParameter("customer") == null ? ""
//						: request.getParameter("customer");
//				String sum = request.getParameter("sum") == null ? "" : request
//						.getParameter("sum");
//				String gameId = request.getParameter("gameId") == null ? ""
//						: request.getParameter("gameId");
//				String section1 = request.getParameter("section1") == null ? ""
//						: request.getParameter("section1");
//				String section2 = request.getParameter("section2") == null ? ""
//						: request.getParameter("section2");
//				String tbOrderSnap = request.getParameter("tbOrderSnap") == null ? "" : new String(request.getParameter("tbOrderSnap").getBytes("UTF-8"), "ISO-8859-1");
//				_log.info("tbOrderSnap decode before:{}", tbOrderSnap);
//				tbOrderSnap = URLDecoder.decode(tbOrderSnap, "GBK");
//				String notifyUrl = request.getParameter("notifyUrl") == null ? "" : request.getParameter("notifyUrl");
//				String sign = request.getParameter("sign") == null ? "" : request.getParameter("sign");
//				String version = request.getParameter("version") == null ? "" : request.getParameter("version");
//				if (coopId.equals("") || tbOrderNo.equals("")
//						|| cardId.equals("") || cardNum.equals("")
//						|| customer.equals("") || sum.equals("")
//						|| tbOrderSnap.equals("") || sign.equals("")
//						|| notifyUrl.equals("")) {
//					errorAck(body, tbOrderNo, tbOrderNo, REQUEST_FAIL, "0101","");
//					return;
//				}
//				if (cfgCoopId.indexOf(coopId) < 0) {
//					_log.warn("coopId:? not in config", coopId);
//					errorAck(body, tbOrderNo, tbOrderNo, ORDER_FAIL, "0306", "");
//					return;
//				}
//				int intCardNum = 0;
//				try {
//					intCardNum = Integer.parseInt(cardNum);
//					if (cardIdMap.get(cardId) == null) {
//						_log.warn("cardId 在配置文件中未发现，cardId = {}", cardId);
//						errorAck(body, tbOrderNo, tbOrderNo, ORDER_FAIL,"0305", "");
//						return;
//					}
//				} catch (Exception e) {
//					errorAck(body, tbOrderNo, tbOrderNo, ORDER_FAIL, "0302", "");
//				}
//				Pattern pattern = Pattern.compile("[0-9]*");
//				Matcher matcher = pattern.matcher(customer);
//				if (!matcher.matches()) {
//					_log.warn("customer is not number, customer = ?", customer);
//					errorAck(body, tbOrderNo, tbOrderNo, ORDER_FAIL, "0306", "");
//					return;
//				}
//				TMallPayBean tmallPayBean = new TMallPayBean(coopId, tbOrderNo,
//						cardId, cardNum, customer, sum, gameId, section1,
//						section2, tbOrderSnap, notifyUrl, sign, version);
//				// 验证签名
//				_log.info("pubkeyValue = {}", pubKeyValue);
//				_log.info("String = {}", tmallPayBean.toString());
//				_log.info("tbOrderSnap = {}", tbOrderSnap);
//				_log.info("sign = {}", sign);
//				/*
//				 * String md5Sign = tmallPayBean.toString() + pubKeyValue;
//				 * if(!SignUtilsImpl.checkTmallSign(md5Sign,sign)) {
//				 * 	   errorAck(body, tbOrderNo, tbOrderNo,REQUEST_FAIL,"0102", "");
//				 * 	   return; 
//				 * }
//				 */
//
//				JSONObject jsonObject=new JSONObject();
//				jsonObject.put("coopId", coopId);
//				jsonObject.put("tbOrderNo", tbOrderNo);
//				jsonObject.put("cardId", cardId);
//				jsonObject.put("cardNum", cardNum);
//				jsonObject.put("customer", customer);
//				jsonObject.put("sum", sum);
//				jsonObject.put("gameId", gameId);
//				jsonObject.put("section1", section1);
//				jsonObject.put("section2", section2);
//				jsonObject.put("tbOrderSnap", tbOrderSnap);
//				String payment_Amount = intCardNum * cardIdMap.get(cardId) + "";
//				Element serviceInformation = null;
//				XmlMessage req = new XmlMessage(true);
//				//String versionType = getVersionType(city_code_new,"0");//传参0 1001类 传1 84210类   返参 1 新 0 旧的
//				String jf3_flag = userResourceConfigService.getValue("jf3_flag","");////增加刷新开关  ,配置为1则表示启用割接地市判断，配置为0则表示按现有的流程
//				if("0".equals(jf3_flag)) {
//					//旧流程
//					serviceInformation = TmallPayUtil.getServiceInfoEle(customer, bankCode, tbOrderNo, payment_Amount, sum);
//				}else {
//					//新流程
//					serviceInformation = DocumentHelper.createElement("Service_Information");
//					Element element = serviceInformation.addElement("Channel_Id");
//					element.setText("200");
//					element = serviceInformation.addElement("DestinationAttr");
//					element.setText("2");
//					element = serviceInformation.addElement("Area_Code");
//					element.setText("027");
//					element = serviceInformation.addElement("Destination_Id");
//					element.setText(customer);
//					element = serviceInformation.addElement("Destination_Id_Type");
//					element.setText("2");
//				}
//				_log.info("=======开关==jf3_flag:"+jf3_flag);
//				
//				String tmallHostId = whConfigService.getValue(AliParam.tmallHostId, "Alibaba1@027.ctnbc-bon.net");
//				String sessionId = DiameterUtils.makeSessionID(tmallHostId);
//				req.setIp(IP);
//				req.setMsgTime(receiveTime);
//				req.setMID(sessionId);
//				req.setUID(tmallHostId);
//				req.setSCID("0".equals(jf3_flag) ? "Recharge.SGW@027.ctnbc-bon.net":"ServAuth.jf3@027.ctnbc-bon.net");
//				req.setSIG(null);
//				req.setREPTAG(0);
//				req.setDATA(serviceInformation.asXML());
//				req.setDataElement(serviceInformation);
//				_log.info("=======DCC请求开始==SICD:"+req.getSCID());
//				// new CallParam对象
//				jsonObject.put("req", req);
//				TMallPayHandle tmallPayHandle = new TMallPayHandle(body,tmallPayBean, tmallResponseService, asynExecutor,tmallRetUrl, pubKeyValue,jsonObject);
//				CallParam callParam = new CallParam(req.getMID(),req.getSCID(), req, req.getUID(), tmallPayHandle);
//				BuzProcessorManager.getInstance().processRequest(callParam);
			} 
			else if (requestPath.endsWith(TmallOrderQuery)) {
				// 订单查询
				_log.info("start tmallOrderQuery......");
				String coopId = request.getParameter("coopId") == null ? ""
						: request.getParameter("coopId");
				String tbOrderNo = request.getParameter("tbOrderNo") == null ? ""
						: request.getParameter("tbOrderNo");
				String sign = request.getParameter("sign") == null ? ""
						: request.getParameter("sign");
				String version = request.getParameter("version") == null ? ""
						: request.getParameter("version");

				if (coopId.equals("") || tbOrderNo.equals("")
						|| sign.equals("")) {
					errorAck(body, tbOrderNo, tbOrderNo, REQUEST_FAIL, "0101",
							"");
					return;
				}

				if (cfgCoopId.indexOf(coopId) < 0) {
					_log.warn("coopId:? not in config", coopId);
					errorAck(body, tbOrderNo, tbOrderNo, ORDER_FAIL, "0306", "");
					return;
				}

				TMallOrderBean tmallOrderBean = new TMallOrderBean(coopId,
						tbOrderNo, sign, version);

				// 验证签名
				String md5Sign = tmallOrderBean.toString() + pubKeyValue;
				if (!SignUtilsImpl.checkTmallSign(md5Sign, sign)) {
					errorAck(body, tbOrderNo, tbOrderNo, REQUEST_FAIL, "0102",
							"");
					return;
				}

				Element serviceInformation = DocumentHelper.createElement("Service_Information");
				
				String jf3_flag = userResourceConfigService.getValue("jf3_flag","");////增加刷新开关  ,配置为1则表示启用割接地市判断，配置为0则表示按现有的流程
				if("0".equals(jf3_flag)) {
					//旧的
					Element element = serviceInformation.addElement("Bank_code");
					element.setText(bankCode);
					element = serviceInformation.addElement("Payment_Serial_Nbr");
					element.setText(tbOrderNo);
				}else {
					//新的
					Element element = serviceInformation.addElement("Channel_Id");
					element.setText("200");
					element = serviceInformation.addElement("Bank_code");
					element.setText("ALIBB");
					element = serviceInformation.addElement("Serial_Type");
					element.setText("0");
					element = serviceInformation.addElement("Payment_Serial_Nbr");
					element.setText(tbOrderNo);
				}
				_log.info("============jf3_flag:"+jf3_flag);
				XmlMessage req = new XmlMessage(true);
				String tmallHostId = whConfigService.getValue(
						AliParam.tmallHostId, "Alibaba1@027.ctnbc-bon.net");
				String sessionId = DiameterUtils.makeSessionID(tmallHostId);
				req.setIp(IP);
				req.setMsgTime(receiveTime);
				req.setMID(sessionId);
				req.setUID(tmallHostId);
				req.setSCID("0".equals(jf3_flag)? "Recharged-Query.SGW@027.ctnbc-bon.net" : "RechargeQuery.jf3@027.ctnbc-bon.net");
				req.setSIG(null);
				req.setREPTAG(0);
				req.setDATA(serviceInformation.asXML());
				req.setDataElement(serviceInformation);
				_log.info("===========开始DCC请求========SCID:"+req.getSCID());
				// new CallParam对象
				TMallOrderQueryHandle tmallOrderQueryHandler = new TMallOrderQueryHandle(body, tmallOrderBean, tmallResponseService,asynExecutor, tmallRetUrl, pubKeyValue);
				CallParam callParam = new CallParam(req.getMID(),req.getSCID(), req, req.getUID(),tmallOrderQueryHandler);
				BuzProcessorManager.getInstance().processRequest(callParam);
			} else if (requestPath.endsWith(TmallOrderCancel)) {
				// 订单取消
				_log.info("start tmallOrderCancel......");
				String coopId = request.getParameter("coopId") == null ? ""
						: request.getParameter("coopId");
				String tbOrderNo = request.getParameter("tbOrderNo") == null ? ""
						: request.getParameter("tbOrderNo");
				String sign = request.getParameter("sign") == null ? ""
						: request.getParameter("sign");
				String version = request.getParameter("version") == null ? ""
						: request.getParameter("version");

				if (coopId.equals("") || tbOrderNo.equals("")
						|| sign.equals("")) {
					errorAck(body, tbOrderNo, tbOrderNo, REQUEST_FAIL, "0101",
							"");
					return;
				}

				if (cfgCoopId.indexOf(coopId) < 0) {
					_log.warn("coopId:? not in config", coopId);
					errorAck(body, tbOrderNo, tbOrderNo, ORDER_FAIL, "0306", "");
					return;
				}

				TMallOrderBean tmallOrderBean = new TMallOrderBean(coopId,
						tbOrderNo, sign, version);

				// 验证签名
				String md5Sign = tmallOrderBean.toString() + pubKeyValue;
				if (!SignUtilsImpl.checkTmallSign(md5Sign, sign)) {
					errorAck(body, tbOrderNo, tbOrderNo, REQUEST_FAIL, "0102",
							"");
					return;
				}

				Element serviceInformation = DocumentHelper
						.createElement("Service_Information");
				Element element = serviceInformation.addElement("Bank_code");
				element.setText(bankCode);
				element = serviceInformation.addElement("Payment_Serial_Nbr");
				element.setText(tbOrderNo);

				XmlMessage req = new XmlMessage(true);
				String tmallHostId = whConfigService.getValue(
						AliParam.tmallHostId, "Alibaba1@027.ctnbc-bon.net");
				String sessionId = DiameterUtils.makeSessionID(tmallHostId);
				req.setIp(IP);
				req.setMsgTime(receiveTime);
				req.setMID(sessionId);
				req.setUID(tmallHostId);
				req.setSCID("Recharged-Rollback.SGW@027.ctnbc-bon.net");
				req.setSIG(null);
				req.setREPTAG(0);
				req.setDATA(serviceInformation.asXML());
				req.setDataElement(serviceInformation);

				// new CallParam对象
				TMallOrderCancelHandler tmallOrderCancelHandler = new TMallOrderCancelHandler(
						body, tmallOrderBean, tmallResponseService,
						asynExecutor, tmallRetUrl, pubKeyValue);
				CallParam callParam = new CallParam(req.getMID(),
						req.getSCID(), req, req.getUID(),
						tmallOrderCancelHandler);
				BuzProcessorManager.getInstance().processRequest(callParam);
			}
			else if (request.getMethod().equalsIgnoreCase("PATCH")) {
			    //修改发票信息API  修改开票信息API
				_log.info("start INVOICEINFORMATION_PATCH......");
				String bodyContent = request.getContent();
				_log.info("bodyContentJSON......"+bodyContent);
				JSONArray jsonArray = JSON.parseArray(bodyContent);
				int one = requestPath.lastIndexOf("/");
				String id = requestPath.substring((one+1),requestPath.length());
				_log.info("id......"+id);
				String lanId = id.substring(0, 4);
//                String serialNumber = object.getString("serialNumber");
//                String buyerAddress = object.getString("buyerAddress");
//                String buyerPhone = object.getString("buyerPhone");
//                String bankAccount = object.getString("bankAccount");
				_log.info("lanId......"+lanId);
				StringBuilder buildStringMes = new StringBuilder();
					//新接口新域名
					buildStringMes.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.asiainfo.com/\">\r\n" + 
							"   <soapenv:Header/>\r\n" + 
							"   <soapenv:Body>\r\n" + 
							"      <web:updateDrawInfo>\r\n" + 
							"         <UpdateDrawInfoRequest>\r\n" + 
							"            <id>"+id+"</id>\r\n" + 
							"            <lanId>"+lanId+"</lanId>\r\n" + 
							"");

			    for (int i = 0; i < jsonArray.size(); i++){
			    	com.alibaba.fastjson.JSONObject s1 = jsonArray.getJSONObject(i);
			    		buildStringMes.append("            <ITEM>\r\n" +
			    				"               <op>"+s1.get("op")+"</op>\r\n" + 
			    				"               <path>"+s1.get("path")+"</path>\r\n" + 
			    				"               <value>"+s1.get("value")+"</value>\r\n" + 
			    				"            </ITEM>\r\n" + 
			    				"");

			    	
			    }
			    	buildStringMes.append("         </UpdateDrawInfoRequest>\r\n" +
			    			"      </web:updateDrawInfo>\r\n" + 
			    			"   </soapenv:Body>\r\n" + 
			    			"</soapenv:Envelope>");

				String webserviceUrl = getURLForJf3( lanId,IS_WUHAN2);//获取URL地址
				String resp =  StringEscapeUtils.unescapeXml(getWebserviceStr(buildStringMes, webserviceUrl));
				String result = "";
				String jsonStr = "";
			    response.set("X-CTG-Request-ID", value);
			    response.set("X-RateLimit-Limit", "60");
			    response.set("X-RateLimit-Remaining", "48");
			    response.set("X-RateLimit-Reset", "14");
				if(!resp.equals("")) {
					String resid = "";
					String rescustId = "";
					String resmobile = "";
					String reseMail = "";
					String resautomaticPush = "";
					String reslanId = "";
					String resinvoiceHeader = "";
					String resbuyerTaxPayerId = "";
					Document doc = null;
				    doc = DocumentHelper.parseText(resp);
				    Element node = doc.getRootElement();
				    List<Element> element = getElement(node);
				    String xmString ="";
				    InvoiceInformation invoiceInformation = new InvoiceInformation();
                    String serialNumber = "";
                    String buyerAddress = "";
                    String buyerPhone = "";
                    String bankAccount = "";
				    for (int j = 0; j < element.size(); j++) {
				    	Element element2 = element.get(j);
					    String name = element2.getName();
			    	    //_log.info("=======================1111========================");
			    	    if(name.equals("RESULT")) {
			    		       result = element2.getText();
			    	    }
			    	    if(name.equals("id")) {
			    	    	   resid = element2.getText();
				    	}
			    	    if(name.equals("custId")) {
			    	    	rescustId = element2.getText();
				        }
			    	    if(name.equals("mobile")) {
			    	    	resmobile = element2.getText();
				    	}
			    	    if(name.equals("eMail")) {
			    	    	reseMail = element2.getText();
				    	}
			    	    if(name.equals("automaticPush")) {
			    	    	resautomaticPush = element2.getText();
				    	}
			    	    if(name.equals("lanId")) {
			    	    	reslanId = element2.getText();
				    	}
			    	    if(name.equals("invoiceHeader")) {
			    	    	resinvoiceHeader = element2.getText();
			    	    	xmString = new String(resinvoiceHeader.toString().getBytes("UTF-8"));
			    	    	//_log.info("bianma------"+new String(resinvoiceHeader.getBytes(encode), encode)));
				    	}
			    	    if(name.equals("buyerTaxPayerId")) {
			    	    	resbuyerTaxPayerId = element2.getText();
				    	}

                        if(name.equals("serialNumber")) {
                            serialNumber = element2.getText();
                        }
                        if(name.equals("buyerAddress")) {
                            buyerAddress = element2.getText();
                        }
                        if(name.equals("buyerPhone")) {
                            buyerPhone = element2.getText();
                        }
                        if(name.equals("bankAccount")) {
                            bankAccount = element2.getText();
                        }
				    }
//				    invoiceInformation.setAutomaticPush(resautomaticPush);
//				    invoiceInformation.setBuyerTaxPayerId(resbuyerTaxPayerId);
//				    invoiceInformation.setCustId(rescustId);
//				    invoiceInformation.seteMail(reseMail);
//				    invoiceInformation.setId(resid);
//				    invoiceInformation.setInvoiceHeader(xmString);
//				    invoiceInformation.setLanId(reslanId);
//				    invoiceInformation.setMobile(resmobile);
                    com.alibaba.fastjson.JSONObject jsonObject=new com.alibaba.fastjson.JSONObject();
                    jsonObject.put("automaticPush",resautomaticPush);
                    jsonObject.put("buyerTaxPayerId",resbuyerTaxPayerId);
                    jsonObject.put("custId",rescustId);
                    jsonObject.put("eMail",reseMail);
                    jsonObject.put("id",resid);
                    jsonObject.put("invoiceHeader",xmString);
                    jsonObject.put("lanId",reslanId);
                    jsonObject.put("mobile",resmobile);
                    jsonObject.put("serialNumber",serialNumber);
                    jsonObject.put("buyerAddress",buyerAddress);
                    jsonObject.put("buyerPhone",buyerPhone);
                    jsonObject.put("bankAccount",bankAccount);

				    if(!result.equals("0")) {
                        String msg="";
                        String reason="";
                        if("2".equals(result)){
                            result="110238";
                            reason="本月修改次数已超过5次，本月不可继续修改";
                        }
				    	MonthlyBillError monthlyBillError = new MonthlyBillError();
				    	monthlyBillError.setCode(result);
				    	monthlyBillError.setMessage(msg);
				    	monthlyBillError.setReason(reason);
				    	monthlyBillError.setReferenceError("");
				    	jsonStr = JSON.toJSONString(monthlyBillError);
                    }else {
//				    	jsonStr = JSON.toJSONString(invoiceInformation);
                        jsonStr = jsonObject.toString();
                    }
                }
				else {
					List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
			    	MonthlyBillError monthlyBillError = new MonthlyBillError();
			    	monthlyBillError.setCode(result);
			    	monthlyBillError.setMessage("");
			    	monthlyBillError.setReason("");
			    	monthlyBillError.setReferenceError("");
			    	monthlyBillErrorList.add(monthlyBillError);
			    	jsonStr = JSON.toJSONString(monthlyBillErrorList);
			    	jsonStr = jsonStr.replaceAll("\\[", "");
				   	jsonStr = jsonStr.replaceAll("\\]", "");
				}
                //记录消息到日志表
                LogUtil.saveLogToABM_TMall(request,result,startTime);
				byte[] resps = jsonStr.getBytes("UTF-8");
				body.write(resps);
				body.close();
			}
			else if(requestPath.endsWith(INVOICEINFORMATION)) {
				if(request.getMethod().equalsIgnoreCase("post")) {
					//新增开票信息API
					_log.info("start INVOICEINFORMATION_POST......");
					String bodyContent = request.getContent();
					JSONObject object=JSONObject.fromObject(bodyContent);
					String id = object.getString("id");
					String custId = object.getString("custId");
					String mobile = object.getString("mobile");
					String eMail = object.getString("eMail");
					
					String automaticPush = object.getString("automaticPush");
					String lanId = object.getString("lanId");
					String invoiceHeader = object.getString("invoiceHeader");
					String buyerTaxPayerId = object.getString("buyerTaxPayerId");
                    String serialNumber = object.getString("serialNumber");
                    String buyerAddress = object.getString("buyerAddress");
                    String buyerPhone = object.getString("buyerPhone");
                    String bankAccount = object.getString("bankAccount");

                    String resultLanIdStr = lanId.substring(0, 5);
					StringBuilder buildStringMes = new StringBuilder();
						//新接口新域名
                    StringBuilder tempStr = new StringBuilder();
                    if(!StringUtil.isBlank(serialNumber)){
                        tempStr.append("<serialNumber>"+serialNumber+"</serialNumber>");
                    }
                    if(!StringUtil.isBlank(buyerAddress)){
                        tempStr.append("<buyerAddress>"+buyerAddress+"</buyerAddress>");
                    }
                    if(!StringUtil.isBlank(buyerPhone)){
                        tempStr.append("<buyerPhone>"+buyerPhone+"</buyerPhone>");
                    }
                    if(!StringUtil.isBlank(bankAccount)){
                        tempStr.append("<bankAccount>"+serialNumber+"</bankAccount>");
                    }
						buildStringMes.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.asiainfo.com/\">\r\n" +
								"   <soapenv:Header/>\r\n" + 
								"   <soapenv:Body>\r\n" + 
								"      <web:newDrawInfo>\r\n" + 
								"         <NewDrawInfoRequest>\r\n" + 
								"            <id>"+id+"</id>\r\n" + 
								"            <custId>"+custId+"</custId>\r\n" + 
								"            <mobile>"+mobile+"</mobile>\r\n" + 
								"            <eMail>"+eMail+"</eMail>\r\n" +
                                                tempStr.toString()+
								"            <automaticPush>"+automaticPush+"</automaticPush>\r\n" + 
								"            <lanId>"+lanId+"</lanId>\r\n" + 
								"            <invoiceHeader>"+invoiceHeader+"</invoiceHeader>\r\n" + 
								"            <buyerTaxPayerId>"+buyerTaxPayerId+"</buyerTaxPayerId>\r\n" + 
								"         </NewDrawInfoRequest>\r\n" + 
								"      </web:newDrawInfo>\r\n" + 
								"   </soapenv:Body>\r\n" + 
								"</soapenv:Envelope>");

					String webserviceUrl = getURLForJf3( resultLanIdStr,IS_WUHAN);//获取URL地址
//					if(resultLanIdStr.equals(IS_WUHAN)) {
//						webserviceUrl = MonthlyBillWUHANURL;
//					}
//					else {
//						webserviceUrl = MonthlyBillHBURL;
//					}
					String resp =  StringEscapeUtils.unescapeXml(getWebserviceStr(buildStringMes, webserviceUrl));
					String result = "";
					String jsonStr = "";
				    response.set("X-CTG-Request-ID", value);
				    response.set("X-RateLimit-Limit", "60");
				    response.set("X-RateLimit-Remaining", "48");
				    response.set("X-RateLimit-Reset", "14");
					if(!resp.equals("")) {
						String resid = "";
						String rescustId = "";
						String resmobile = "";
						String reseMail = "";
						
						String resautomaticPush = "";
						String reslanId = "";
						String resinvoiceHeader = "";
						String resbuyerTaxPayerId = "";
                         serialNumber = "";
                         buyerAddress = "";
                         buyerPhone = "";
                         bankAccount = "";
						Document doc = null;
					    doc = DocumentHelper.parseText(resp);
					    Element node = doc.getRootElement();
					    List<Element> element = getElement(node);
					    String xmString ="";
					    List<InvoiceInformation> InvoiceInformationList = new ArrayList<InvoiceInformation>();
					    InvoiceInformation invoiceInformation = new InvoiceInformation();
					    for (int j = 0; j < element.size(); j++) {
					    	Element element2 = element.get(j);
						    String name = element2.getName();
				    	    //_log.info("=======================1111========================");
				    	    if(name.equals("RESULT")) {
				    		       result = element2.getText();
				    	    }
				    	    if(name.equals("id")) {
				    	    	   resid = element2.getText();
					    	}
				    	    if(name.equals("custId")) {
				    	    	rescustId = element2.getText();
					        }
				    	    if(name.equals("mobile")) {
				    	    	resmobile = element2.getText();
					    	}
				    	    if(name.equals("eMail")) {
				    	    	reseMail = element2.getText();
					    	}
				    	    if(name.equals("automaticPush")) {
				    	    	resautomaticPush = element2.getText();
					    	}
				    	    if(name.equals("lanId")) {
				    	    	reslanId = element2.getText();
					    	}
				    	    if(name.equals("invoiceHeader")) {
				    	    	resinvoiceHeader = element2.getText();
				    	    	xmString = new String(resinvoiceHeader.toString().getBytes("UTF-8"));
				    	    	//_log.info("bianma------"+new String(resinvoiceHeader.getBytes(encode), encode)));
					    	}
				    	    if(name.equals("buyerTaxPayerId")) {
				    	    	resbuyerTaxPayerId = element2.getText();
					    	}
                            if(name.equals("serialNumber")) {
                                serialNumber = element2.getText();
                            }
                            if(name.equals("buyerAddress")) {
                                buyerAddress = element2.getText();
                            }
                            if(name.equals("buyerPhone")) {
                                buyerPhone = element2.getText();
                            }
                            if(name.equals("bankAccount")) {
                                bankAccount = element2.getText();
                            }
					    }
                        com.alibaba.fastjson.JSONObject jsonObject=new com.alibaba.fastjson.JSONObject();
                        jsonObject.put("automaticPush",resautomaticPush);
                        jsonObject.put("buyerTaxPayerId",resbuyerTaxPayerId);
                        jsonObject.put("custId",rescustId);
                        jsonObject.put("eMail",reseMail);
                        jsonObject.put("id",resid);
                        jsonObject.put("invoiceHeader",xmString);
                        jsonObject.put("lanId",reslanId);
                        jsonObject.put("mobile",resmobile);
                        jsonObject.put("serialNumber",serialNumber);
                        jsonObject.put("buyerAddress",buyerAddress);
                        jsonObject.put("buyerPhone",buyerPhone);
                        jsonObject.put("bankAccount",bankAccount);
                        List<com.alibaba.fastjson.JSONObject> objectList=new ArrayList<>();
                        objectList.add(jsonObject);


                        invoiceInformation.setAutomaticPush(resautomaticPush);
					    invoiceInformation.setBuyerTaxPayerId(resbuyerTaxPayerId);
					    invoiceInformation.setCustId(rescustId);
					    invoiceInformation.seteMail(reseMail);
					    invoiceInformation.setId(resid);
					    invoiceInformation.setInvoiceHeader(xmString);
					    invoiceInformation.setLanId(reslanId);
					    invoiceInformation.setMobile(resmobile);
					    InvoiceInformationList.add(invoiceInformation);
					    if(!result.equals("0")) {
							List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
					    	MonthlyBillError monthlyBillError = new MonthlyBillError();
					    	monthlyBillError.setCode(result);
					    	monthlyBillError.setMessage("");
					    	monthlyBillError.setReason("");
					    	monthlyBillError.setReferenceError("");
					    	monthlyBillErrorList.add(monthlyBillError);
					    	jsonStr = JSON.toJSONString(monthlyBillErrorList);
                        }else {
//                            jsonStr = JSON.toJSONString(InvoiceInformationList);
                            jsonStr = JSON.toJSONString(objectList);
                        }
                    }
					else {
						List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
				    	MonthlyBillError monthlyBillError = new MonthlyBillError();
				    	monthlyBillError.setCode(result);
				    	monthlyBillError.setMessage("");
				    	monthlyBillError.setReason("");
				    	monthlyBillError.setReferenceError("");
				    	monthlyBillErrorList.add(monthlyBillError);
				    	jsonStr = JSON.toJSONString(monthlyBillErrorList);
                    }
                    jsonStr = jsonStr.replaceAll("\\[", "");
                    jsonStr = jsonStr.replaceAll("\\]", "");
                    //记录消息到日志表
                    LogUtil.saveLogToABM_TMall(request,result,startTime);
					byte[] resps = jsonStr.getBytes("UTF-8");
					body.write(resps);
					body.close();
				}
				else if(request.getMethod().equalsIgnoreCase("get")){
				    //查询开票信息API
					_log.info("start INVOICEINFORMATION_GET......");
					String serialNumber = request.getParameter("serialNumber") == null ? "": request.getParameter("serialNumber");
					String lanId = request.getParameter("lanId") == null ? "": request.getParameter("lanId");
					String type = request.getParameter("type") == null ? "": request.getParameter("type");
					String resultLanIdStr = lanId.substring(0, 5);
					StringBuilder buildStringMes = new StringBuilder();

                    String buyerAddress = request.getParameter("buyerAddress");
                    String buyerPhone = request.getParameter("buyerPhone");
                    String bankAccount = request.getParameter("bankAccount");
                    StringBuilder tempStr = new StringBuilder();
                    if(!StringUtil.isBlank(buyerAddress)){
                        tempStr.append("<buyerAddress>"+buyerAddress+"</buyerAddress>");
                    }
                    if(!StringUtil.isBlank(buyerPhone)){
                        tempStr.append("<buyerPhone>"+buyerPhone+"</buyerPhone>");
                    }
                    if(!StringUtil.isBlank(bankAccount)){
                        tempStr.append("<bankAccount>"+serialNumber+"</bankAccount>");
                    }
						//新接口新域名
						buildStringMes.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.asiainfo.com/\">\r\n" + 
								"   <soapenv:Header/>\r\n" + 
								"   <soapenv:Body>\r\n" + 
								"      <web:queryDrawInfo>\r\n" + 
								"         <QueryDrawInfoRequest>\r\n" + 
								"            <lanId>"+lanId+"</lanId>\r\n" + 
								"            <serialNumber>"+serialNumber+"</serialNumber>\r\n" +
                                        tempStr.toString()+
								"            <type>"+type+"</type>\r\n" + 
								"         </QueryDrawInfoRequest>\r\n" + 
								"      </web:queryDrawInfo>\r\n" + 
								"   </soapenv:Body>\r\n" + 
								"</soapenv:Envelope>");

					
					String webserviceUrl = getURLForJf3( resultLanIdStr,IS_WUHAN);//获取URL地址
					String resp =  StringEscapeUtils.unescapeXml(getWebserviceStr(buildStringMes, webserviceUrl));
                    String jsonStr = "";
                    String result = "";
                    try {
                        response.set("X-CTG-Request-ID", value);
                        response.set("X-RateLimit-Limit", "60");
                        response.set("X-RateLimit-Remaining", "48");
                        response.set("X-RateLimit-Reset", "14");
                        if(!resp.equals("")) {
                                _log.info("=======================resp========================"+resp);
                                Document doc = null;
                                doc = DocumentHelper.parseText(resp);
                                Element node = doc.getRootElement();
                                List<Element> element = getElement(node);
                                String id = "";
                                String custId = "";
                                String mobile = "";
                                String eMail = "";
                                String automaticPush = "";
                                String lanIds = "";
                                String invoiceHeader = "";
                                String buyerTaxPayerId = "";

                                InvoiceInformation information = new InvoiceInformation();
                                for (int j = 0; j < element.size(); j++) {
                                  Element element2 = element.get(j);
                                  String name = element2.getName();
                                  if(name.equals("RESULT")) {
                                      result = element2.getText();
                                  }
                                  if(name.equals("id")) {
                                      id = element2.getText();
                                  }
                                  if(name.equals("custId")) {
                                      custId = element2.getText();
                                  }
                                  if(name.equals("mobile")) {
                                      mobile = element2.getText();
                                  }
                                  if(name.equals("eMail")) {
                                      eMail = element2.getText();
                                  }
                                  if(name.equals("automaticPush")) {
                                      automaticPush = element2.getText();
                                  }
                                  if(name.equals("lanId")) {
                                      lanIds = element2.getText();
                                  }
                                  if(name.equals("invoiceHeader")) {
                                      invoiceHeader = element2.getText();
                                  }
                                  if(name.equals("buyerTaxPayerId")) {
                                      buyerTaxPayerId = element2.getText();
                                  }

                                    if(name.equals("serialNumber")) {
                                        serialNumber = element2.getText();
                                    }
                                    if(name.equals("buyerAddress")) {
                                        buyerAddress = element2.getText();
                                    }
                                    if(name.equals("buyerPhone")) {
                                        buyerPhone = element2.getText();
                                    }
                                    if(name.equals("bankAccount")) {
                                        bankAccount = element2.getText();
                                    }
                                }


                            com.alibaba.fastjson.JSONObject jsonObject=new com.alibaba.fastjson.JSONObject();
                            jsonObject.put("automaticPush",automaticPush);
                            jsonObject.put("buyerTaxPayerId",buyerTaxPayerId);
                            jsonObject.put("custId",custId);
                            jsonObject.put("eMail",eMail);
                            jsonObject.put("id",id);
                            jsonObject.put("invoiceHeader",invoiceHeader);
                            jsonObject.put("lanId",lanIds);
                            jsonObject.put("mobile",mobile);
                            jsonObject.put("serialNumber",serialNumber);
                            jsonObject.put("buyerAddress",buyerAddress);
                            jsonObject.put("buyerPhone",buyerPhone);
                            jsonObject.put("bankAccount",bankAccount);
                            List<com.alibaba.fastjson.JSONObject> objectList=new ArrayList<>();
                            objectList.add(jsonObject);
                                if(!result.equals("0")) {
                                    List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
                                    MonthlyBillError monthlyBillError = new MonthlyBillError();
                                    if (!result.equals("1")) {
                                        monthlyBillError.setCode(result);
                                        monthlyBillError.setMessage("");
                                        monthlyBillError.setReason("");
                                        monthlyBillError.setReferenceError("");
                                    }
                                    monthlyBillErrorList.add(monthlyBillError);
                                    jsonStr = JSON.toJSONString(monthlyBillErrorList);
                                }else {
                                    _log.info("=======================resp111========================"+resp);
                                    jsonStr = JSON.toJSONString(objectList);
                                    _log.info("=======================respXMLJSON========================");
                                    _log.info("---返回的消息---"+jsonStr);
                                    _log.info("=======================respXML========================");
                                }
                        }else {
                            List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
                            MonthlyBillError monthlyBillError = new MonthlyBillError();
                            monthlyBillError.setCode(result);
                            monthlyBillError.setMessage("");
                            monthlyBillError.setReason("");
                            monthlyBillError.setReferenceError("");
                            monthlyBillErrorList.add(monthlyBillError);
                            jsonStr = JSON.toJSONString(monthlyBillErrorList);
                        }
                    }catch (Exception e){
                        _log.error("",e);
                    }
                    jsonStr = jsonStr.replaceAll("\\[", "");
                    jsonStr = jsonStr.replaceAll("\\]", "");
                    //记录消息到日志表
                    LogUtil.saveLogToABM_TMall(request,result,startTime);

					byte[] resps = jsonStr.getBytes("UTF-8");
					body.write(resps);
					body.close();
				}
			}
			else if(requestPath.endsWith(ISSUEINVOICE)) {
			    //开具发票API
				_log.info("start ISSUEINVOICE......");
				String bodyContent = request.getContent();
				_log.info("bodyContent......"+bodyContent);
				com.alibaba.fastjson.JSONObject object=com.alibaba.fastjson.JSONObject.parseObject(bodyContent);
				String issueId = object.getString("issueId");
				String type = object.getString("type");
				String lanId = object.getString("lanId");
				String resultLanIdStr = lanId.substring(0, 5);
				StringBuilder buildStringMes = new StringBuilder();
				JSONArray familys =object.getJSONArray("objects");
                String amounts = object.getString("amounts");

//				String urlForJf4 = getURLForJf4( resultLanIdStr,IS_WUHAN);//0旧的 1新的
                //组装报文XML 头部
					buildStringMes.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.asiainfo.com/\">\r\n" +
							"   <soapenv:Header/>\r\n" + 
							"   <soapenv:Body>\r\n" + 
							"      <web:drawEInvoice>\r\n" + 
							"         <DrawEInvoiceRequest>\r\n" + 
							"            <requestId>"+valueOriginalId+"</requestId>\r\n" + 
							"            <issueId>"+issueId+"</issueId>\r\n" + 
							"            <type>"+type+"</type>\r\n" + 
							"            <lanId>"+lanId+"</lanId>\r\n" +
                            "<amounts>"+amounts+"</amounts>       ");

				
				JSONArray family =object.getJSONArray("objects");
				_log.info("bodyContent111......"+bodyContent);
				for (int i = 0; i < family.size(); i++){
					com.alibaba.fastjson.JSONObject s1 = family.getJSONObject(i);
					String id = (String)s1.get("id");
					String productId = (String)s1.get("productId");
					String billMonth = "";
					String billDate = "";
					String OrderNumber = "";
					if(type.equals("1000")) {
						billMonth = (String)s1.get("billMonth");
					}
					else if(type.equals("1100")) {
						billDate = (String)s1.get("paymentdate");
					}
					else {
						billDate = (String)s1.get("orderDate");
						OrderNumber = (String)s1.get("orderNumber");
					}
					String amount = (String)s1.get("amount");
					String status = (String)s1.get("status");
                    String invoiceId = (String)s1.get("invoiceId");

                    buildStringMes.append("            <object>\r\n" +
                            "<invoiceId>"+invoiceId+"</invoiceId>"+
                            "               <amount>"+amount+"</amount>\r\n" +
                            "               <billDate>"+billDate+"</billDate>\r\n" +
                            "               <billMonth>"+billMonth+"</billMonth>\r\n" +
                            "               <ID>"+id+"</ID>\r\n" +
                            "               <orderNumber>"+OrderNumber+"</orderNumber>\r\n" +
                            "               <productId>"+productId+"</productId>\r\n" +
                            "               <status>"+status+"</status>\r\n" +
                            "            </object>");

				}
				//组装报文XML 尾部
					buildStringMes.append("         </DrawEInvoiceRequest>\r\n" +
							"      </web:drawEInvoice>\r\n" + 
							"   </soapenv:Body>\r\n" + 
							"</soapenv:Envelope>");
				_log.info("buildStringMes......"+buildStringMes.toString());
				String webserviceUrl = getURLForJf3(  resultLanIdStr,IS_WUHAN);//获取URL地址
				String resp =  StringEscapeUtils.unescapeXml(getWebserviceStr(buildStringMes, webserviceUrl));
				String result = "";
				String jsonStr = "";
				String messAgeStr = "";
			    response.set("X-CTG-Request-ID", value);
			    response.set("X-RateLimit-Limit", "60");
			    response.set("X-RateLimit-Remaining", "48");
			    response.set("X-RateLimit-Reset", "14");
				if(!resp.equals("")) {
					Document doc = null;
				    doc = DocumentHelper.parseText(resp);
				    Element node = doc.getRootElement();
				    List<Element> element = getElement(node);
				    for (int j = 0; j < element.size(); j++) {
				    	Element element2 = element.get(j);
					    String name = element2.getName();
			    	    //_log.info("=======================1111========================");
			    	    if(name.equals("RESULT")) {
			    		   result = element2.getText();
			    		   break;
			    	    }
				    }
			    	for (int j = 0; j < element.size(); j++) {
			    		Element element2 = element.get(j);
					    String name = element2.getName();
					    if(name.equals("RESULTINFO")) {
					    	messAgeStr = element2.getText();
			    		    break;
				    	}
			    	}
				}
//				&& bodyContent.contains("amounts")
				if("0".equals(result) ){
				    //重新处理 增加status字段返回给集团。
//                    JSONArray familys =object.getJSONArray("objects");
//                    计费接返回result=0时，RESULTINFO=发票已开具，status刷成1，
//                    RESULTINFO=发票开具中，status刷成3。其它的传集团入参status；
                    for (int i = 0; i < familys.size(); i++) {
                        com.alibaba.fastjson.JSONObject jsonObject = familys.getJSONObject(i);
                        if("发票已开具".equals(messAgeStr)){
                            jsonObject.put("status","1");
                        }else if("发票开具中".equals(messAgeStr)){
                            jsonObject.put("status","3");
                        }
                    }
                    jsonStr=object.toString();
                }else{
                    MonthlyBillError monthlyBillError = new MonthlyBillError();
                    monthlyBillError.setCode(result);
                    monthlyBillError.setMessage(messAgeStr);
                    monthlyBillError.setReason("");
                    monthlyBillError.setReferenceError("");
                    jsonStr = JSON.toJSONString(monthlyBillError);
                }
				_log.info("jsonStr:"+jsonStr);
                //记录消息到日志表
                LogUtil.saveLogToABM_TMall(request,result,startTime);
				byte[] resps = jsonStr.getBytes("UTF-8");
				body.write(resps);
				body.close();
				
			}
			else if(requestPath.endsWith(INVOICE)) {
			    //发票API
				_log.info("isGet"+request.getMethod().equalsIgnoreCase("get"));
				_log.info("isPOST"+request.getMethod().equalsIgnoreCase("post"));
				_log.info("start INVOICE......");
				String invoiceIdRequest = request.getParameter("invoiceId") == null ? "": request.getParameter("invoiceId");
				String lanId = request.getParameter("lanId") == null ? "": request.getParameter("lanId");
				String resultLanIdStr = lanId.substring(0, 5);
				StringBuilder buildStringMes = new StringBuilder();
				String urlForJf4 = getURLForJf4( resultLanIdStr,IS_WUHAN);//0旧的 1新的
				if("1".equals(urlForJf4)) {
					buildStringMes.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.asiainfo.com/\">\r\n" + 
							"   <soapenv:Header/>\r\n" + 
							"   <soapenv:Body>\r\n" + 
							"      <web:queryEInvoiceDetail>\r\n" + 
							"         <QueryEInvoiceDetailRequest>\r\n" + 
							"            <lanId>"+lanId+"</lanId>\r\n" + 
							"            <invoiceId>"+invoiceIdRequest+"</invoiceId>\r\n" + 
							"         </QueryEInvoiceDetailRequest>\r\n" + 
							"      </web:queryEInvoiceDetail>\r\n" + 
							"   </soapenv:Body>\r\n" + 
							"</soapenv:Envelope>");
				}else {
					buildStringMes.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.hquery.ailk.com/\">");
					buildStringMes.append("<soapenv:Header/>");
					buildStringMes.append("<soapenv:Body>");
					buildStringMes.append("<m:QueryEInvoiceDetailRequest xmlns:m=\"http://ygz.service.boss/client/\">");
					buildStringMes.append("<m:lanId>"+lanId+"</m:lanId>");
					buildStringMes.append("<m:invoiceId>"+invoiceIdRequest+"</m:invoiceId>");
					buildStringMes.append("</m:QueryEInvoiceDetailRequest>");
					buildStringMes.append("</soapenv:Body>");
					buildStringMes.append("</soapenv:Envelope>");
				}
				String webserviceUrl = getURLForJf3( resultLanIdStr,IS_WUHAN);//获取URL地址
//				if(resultLanIdStr.equals(IS_WUHAN)) {
//					webserviceUrl = MonthlyBillWUHANURL;
//				}
//				else {
//					webserviceUrl = MonthlyBillHBURL;
//				}
				List<com.hp.bon.sgw.wh.bean.Invoice> invoiceList = new ArrayList<com.hp.bon.sgw.wh.bean.Invoice>();
				String resp =  StringEscapeUtils.unescapeXml(getWebserviceStr(buildStringMes, webserviceUrl));
				resp = resp.replaceAll("&", "&amp;");
				_log.info("=======================返回的xmlresp========================"+resp);
				String result = "";
				String jsonStr = "";
			    response.set("X-CTG-Request-ID", value);
			    response.set("X-RateLimit-Limit", "60");
			    response.set("X-RateLimit-Remaining", "48");
			    response.set("X-RateLimit-Reset", "14");
				if(!resp.equals("")) {
					Document doc = null;
				    doc = DocumentHelper.parseText(resp);
				    Element node = doc.getRootElement();
				    List<Element> element = getElement(node);
				    String url = "";
			    	String invoicedate = "";
			    	String invoiceCode = "";
			    	String invoiceNo = "";
			    	String invoiceId = "";
			    	String values = "";
			    	String type = "";
			        com.hp.bon.sgw.wh.bean.Invoice invoice = new com.hp.bon.sgw.wh.bean.Invoice();
				    for (int j = 0; j < element.size(); j++) {
				      Element element2 = element.get(j);
				      String name = element2.getName();
			    	  //_log.info("=======================1111========================");
			    	  if(name.equals("RESULT")) {
			    		  result = element2.getText();
			    	  }
			    	  if(name.equals("url")) {
			    		  url = element2.getText();
			    	  }
					  if(name.equals("invoiceDate")) {
						  invoicedate = element2.getText();	    		  
					  }
					  if(name.equals("invoiceCode")) {
						  invoiceCode = element2.getText();
					  }
					  if(name.equals("invoiceNo")) {
						  invoiceNo = element2.getText();
					  }
					  if(name.equals("invoiceId")) {
						  invoiceId = element2.getText();
					  }
	                  if(name.equals("value")) {
	                	  values = element2.getText();
					  }
					  if(name.equals("type")) {
						  type = element2.getText();
					  }
				    
				    }
				    invoice.setInvoiceCode(invoiceCode);
			    	invoice.setInvoiceDate(invoicedate);
			    	invoice.setInvoiceId(invoiceId);
			    	invoice.setInvoiceNo(invoiceNo);;
			    	invoice.setType(type);
			    	invoice.setValue(values);
			    	invoice.setUrl(url);
			    	invoiceList.add(invoice);
			    	_log.info("=======================实体invoiceList========================"+resp);
			    	if(!result.equals("0")) {
			    		List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
			    		if(result.equals("1")) {
			    			MonthlyBillError monthlyBillError = new MonthlyBillError();
				    		monthlyBillErrorList.add(monthlyBillError);
				    		jsonStr = JSON.toJSONString(monthlyBillErrorList);
				    		jsonStr = jsonStr.replaceAll("\\[", "");
				    	   	jsonStr = jsonStr.replaceAll("\\]", "");
				    	}
				    	else {
				    		MonthlyBillError monthlyBillError = new MonthlyBillError();
					    	monthlyBillError.setCode(result);
					    	monthlyBillError.setMessage("");
					    	monthlyBillError.setReason("");
					    	monthlyBillError.setReferenceError("");
					    	monthlyBillErrorList.add(monthlyBillError);
					    	jsonStr = JSON.toJSONString(monthlyBillErrorList);
					    	jsonStr = jsonStr.replaceAll("\\[", "");
						   	jsonStr = jsonStr.replaceAll("\\]", "");	
				    	}
				    	
				    }
				    else {
					    _log.info("=======================resp111========================"+resp);
					    jsonStr = JSON.toJSONString(invoiceList);
					    jsonStr = jsonStr.replaceAll("\\[", "");
					   	jsonStr = jsonStr.replaceAll("\\]", "");
					    _log.info("=======================respXMLJSON========================");
					    _log.info("---返回的消息---"+jsonStr);
					    _log.info("=======================respXML========================");
				    }
				}
				else {
					List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
					MonthlyBillError monthlyBillError = new MonthlyBillError();
			    	monthlyBillError.setCode(result);
			    	monthlyBillError.setMessage("");
			    	monthlyBillError.setReason("");
			    	monthlyBillError.setReferenceError("");
			    	monthlyBillErrorList.add(monthlyBillError);
			    	jsonStr = JSON.toJSONString(monthlyBillErrorList);
			    	jsonStr = jsonStr.replaceAll("\\[", "");
				   	jsonStr = jsonStr.replaceAll("\\]", "");
				}

                //记录消息到日志表
                LogUtil.saveLogToABM_TMall(request,result,startTime);

				byte[] resps = jsonStr.getBytes("UTF-8");
				body.write(resps);
				body.close();
			} 
			else if(requestPath.endsWith(INVOICE_HB)) {
				_log.info("start INVOICE_POST......");
				String url = EopInvoiceURL;
				String bodyContent = request.getContent();
				PrintWriter out = null;
		        BufferedReader in = null;
		        String result = "";
		        _log.info("bodyContent......"+bodyContent);
		        try {
		        	URL realUrl = new URL(url);
			        URLConnection conn = realUrl.openConnection();
			        conn.setRequestProperty("accept", "*/*");
		            conn.setRequestProperty("connection", "Keep-Alive");
		            conn.setRequestProperty("user-agent",
		                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		            // 发送POST请求必须设置如下两行
		            conn.setDoOutput(true);
		            conn.setDoInput(true);
		            // 获取URLConnection对象对应的输出流
		            out = new PrintWriter(conn.getOutputStream());
		            // 发送请求参数
		            out.print(bodyContent);
		            // flush输出流的缓冲
		            out.flush();
		            // 定义BufferedReader输入流来读取URL的响应
		            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		            String line;
		            while ((line = in.readLine()) != null) {
		                result += line;
		            }
				} catch (Exception e) {
					_log.info("发送GET请求出现异常！" + e.getMessage());
				}
		        finally {
		            try {
		                if (in != null) {
		                    in.close();
		                }
		            } catch (Exception e2) {
		                e2.printStackTrace();
		            }
		        }
		        byte[] resps = result.getBytes("UTF-8");
				body.write(resps);
				body.close();
		        
			}
			
			else if(requestPath.endsWith(ORDERONEITEM)) {
			    //营业厅订单费用API
				_log.info("start ORDERONEITEM......");
				String serialNumber = request.getParameter("serialNumber") == null ? "": request.getParameter("serialNumber");
				String lanId = request.getParameter("lanId") == null ? "": request.getParameter("lanId");
				String resultLanIdStr = lanId.substring(0, 5);
				StringBuilder buildStringMes = new StringBuilder();
				String webserviceUrl = getURLForJf3( resultLanIdStr,IS_WUHAN);//获取URL地址
				String urlForJf4 = getURLForJf4( resultLanIdStr,IS_WUHAN);//0旧的 1新的
				if("1".equals(urlForJf4)) {
					//新接口新域名
					buildStringMes.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.asiainfo.com/\">\r\n" + 
							"   <soapenv:Header/>\r\n" + 
							"   <soapenv:Body>\r\n" + 
							"      <web:queryEInvoice>\r\n" + 
							"         <QueryEInvoiceRequest>\r\n" + 
							"            <lanId>"+lanId+"</lanId>\r\n" + 
							"            <serialNumber>"+serialNumber+"</serialNumber>\r\n" + 
							"            <apiType>"+3+"</apiType>\r\n" + 
							"         </QueryEInvoiceRequest>\r\n" + 
							"      </web:queryEInvoice>\r\n" + 
							"   </soapenv:Body>\r\n" + 
							"</soapenv:Envelope>");
				}else {
					buildStringMes.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.hquery.ailk.com/\">");
					buildStringMes.append("<soapenv:Header/>");
					buildStringMes.append("<soapenv:Body>");
					buildStringMes.append("<m:QueryEInvoiceRequest xmlns:m=\"http://ygz.service.boss/client/\">");
					buildStringMes.append("<m:lanId>"+lanId+"</m:lanId>");
					buildStringMes.append("<m:serialNumber>"+serialNumber+"</m:serialNumber>");
					buildStringMes.append("<m:apiType>"+3+"</m:apiType>");
					buildStringMes.append("</m:QueryEInvoiceRequest>");
					buildStringMes.append("</soapenv:Body>");
					buildStringMes.append("</soapenv:Envelope>");
				}
				List<com.hp.bon.sgw.wh.bean.OrderOneItem> OrderOneItemList = new ArrayList<com.hp.bon.sgw.wh.bean.OrderOneItem>();
				String resp =  StringEscapeUtils.unescapeXml(getWebserviceStr(buildStringMes, webserviceUrl));
				String result = "";
				String jsonStr = "";
			    response.set("X-CTG-Request-ID", value);
			    response.set("X-RateLimit-Limit", "60");
			    response.set("X-RateLimit-Remaining", "48");
			    response.set("X-RateLimit-Reset", "14");
                resp=resp.replace("<ITEM/>","");
				if(!resp.equals("")) {
					    _log.info("=======================resp========================"+resp);
					    Document doc = null;
					    doc = DocumentHelper.parseText(resp);
					    Element node = doc.getRootElement();
					    List<Element> element = getElement(node);
					    for (int j = 0; j < element.size(); j++) {
					      Element element2 = element.get(j);
					      String name = element2.getName();
					      if ("ITEM".equalsIgnoreCase(name)) {
					    	  com.hp.bon.sgw.wh.bean.OrderOneItem orderOneItem = new com.hp.bon.sgw.wh.bean.OrderOneItem();
					    	  _log.info("=======================1111========================");
					    	  String id = element2.element("ID").getText();
					    	  _log.info("=======================id========================"+id);
					    	  String productId = element2.element("productId").getText();
					    	  String paymentdate = element2.element("billDate").getText();
					    	  String amount = element2.element("amount").getText();
					    	  String invoiceId = element2.element("invoiceId").getText();
					    	  String status = element2.element("Status") == null ? element2.element("status").getText() : element2.element("Status").getText();
					    	  String orderNumber = element2.element("OrderNumber") == null ?element2.element("orderNumber").getText() : element2.element("OrderNumber").getText();
					    	  orderOneItem.setAmount(amount);
					    	  orderOneItem.setOrderNumber(orderNumber);
					    	  orderOneItem.setOrderDate(paymentdate);
					    	  orderOneItem.setId(id);
					    	  orderOneItem.setInvoiceId(invoiceId);
					    	  orderOneItem.setProductId(productId);
					    	  orderOneItem.setStatus(status);
					    	  OrderOneItemList.add(orderOneItem);
					      }
					      if("RESULT".equalsIgnoreCase(name)) {
					    	  result = element2.getText();
					      }
					    }
					    List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
					    if(!result.equals("0")) {
					    	if(result.equals("1")) {
					    		jsonStr = JSON.toJSONString(monthlyBillErrorList);
					    	}
					    	else {
					    		MonthlyBillError monthlyBillError = new MonthlyBillError();
						    	monthlyBillError.setCode(result);
						    	monthlyBillError.setMessage("");
						    	monthlyBillError.setReason("");
						    	monthlyBillError.setReferenceError("");
						    	monthlyBillErrorList.add(monthlyBillError);
						    	jsonStr = JSON.toJSONString(monthlyBillErrorList);
					    	}
					    	
					    }
					    else {
						    _log.info("=======================resp111========================"+resp);
						    jsonStr = JSON.toJSONString(OrderOneItemList);
						    _log.info("=======================respXMLJSON========================");
						    _log.info("---返回的消息---"+jsonStr);
						    _log.info("=======================respXML========================");
					    }
				}
				else {
					List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
					MonthlyBillError monthlyBillError = new MonthlyBillError();
			    	monthlyBillError.setCode(result);
			    	monthlyBillError.setMessage("");
			    	monthlyBillError.setReason("");
			    	monthlyBillError.setReferenceError("");
			    	monthlyBillErrorList.add(monthlyBillError);
			    	jsonStr = JSON.toJSONString(monthlyBillErrorList);
				}
                //记录消息到日志表
                LogUtil.saveLogToABM_TMall(request,result,startTime);

				byte[] resps = jsonStr.getBytes("UTF-8");
				body.write(resps);
				body.close();
			}
			else if (requestPath.endsWith(PAYMENT)) {
			    //缴费API
				_log.info("start PAYMENT......");
				String serialNumber = request.getParameter("serialNumber") == null ? "": request.getParameter("serialNumber");
				String lanId = request.getParameter("lanId") == null ? "": request.getParameter("lanId");
				String resultLanIdStr = lanId.substring(0, 5);
				StringBuilder buildStringMes = new StringBuilder();
				String webserviceUrl = getURLForJf3(  resultLanIdStr,IS_WUHAN);//获取URL地址
				String urlForJf4 = getURLForJf4( resultLanIdStr,IS_WUHAN);//0旧的 1新的
				if("1".equals(urlForJf4)) {
					//新接口新域名
					buildStringMes.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.asiainfo.com/\">\r\n" + 
							"   <soapenv:Header/>\r\n" + 
							"   <soapenv:Body>\r\n" + 
							"      <web:queryEInvoice>\r\n" + 
							"         <QueryEInvoiceRequest>\r\n" + 
							"            <lanId>"+lanId+"</lanId>\r\n" + 
							"            <serialNumber>"+serialNumber+"</serialNumber>\r\n" + 
							"            <apiType>"+2+"</apiType>\r\n" + 
							"         </QueryEInvoiceRequest>\r\n" + 
							"      </web:queryEInvoice>\r\n" + 
							"   </soapenv:Body>\r\n" + 
							"</soapenv:Envelope>");
				}else {
					buildStringMes.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.hquery.ailk.com/\">");
					buildStringMes.append("<soapenv:Header/>");
					buildStringMes.append("<soapenv:Body>");
					buildStringMes.append("<m:QueryEInvoiceRequest xmlns:m=\"http://ygz.service.boss/client/\">");
					buildStringMes.append("<m:lanId>"+lanId+"</m:lanId>");
					buildStringMes.append("<m:serialNumber>"+serialNumber+"</m:serialNumber>");
					buildStringMes.append("<m:apiType>"+2+"</m:apiType>");
					buildStringMes.append("</m:QueryEInvoiceRequest>");
					buildStringMes.append("</soapenv:Body>");
					buildStringMes.append("</soapenv:Envelope>");
				}
				List<com.hp.bon.sgw.wh.bean.Payment> paymentList = new ArrayList<com.hp.bon.sgw.wh.bean.Payment>();
				String resp =  StringEscapeUtils.unescapeXml(getWebserviceStr(buildStringMes, webserviceUrl));
				String result = "";
				String jsonStr = "";
			    response.set("X-CTG-Request-ID", value);
			    response.set("X-RateLimit-Limit", "60");
			    response.set("X-RateLimit-Remaining", "48");
			    response.set("X-RateLimit-Reset", "14");
                resp=resp.replace("<ITEM/>","");
				if(!resp.equals("")) {
					    _log.info("=======================resp========================"+resp);
					    Document doc = null;
					    doc = DocumentHelper.parseText(resp);
					    Element node = doc.getRootElement();
					    List<Element> element = getElement(node);
					    for (int j = 0; j < element.size(); j++) {
					      Element element2 = element.get(j);
					      String name = element2.getName();
					      if ("ITEM".equalsIgnoreCase(name)) {
					    	  com.hp.bon.sgw.wh.bean.Payment payment = new com.hp.bon.sgw.wh.bean.Payment();
					    	  _log.info("=======================1111========================");
					    	  String id = element2.element("ID").getText();
					    	  _log.info("=======================id========================"+id);
					    	  String productId = element2.element("productId").getText();
					    	  String paymentdate = element2.element("billDate").getText();
					    	  String amount = element2.element("amount").getText();
					    	  String invoiceId = element2.element("invoiceId").getText();
					    	  String status = element2.element("Status") == null ? element2.element("status").getText():element2.element("Status").getText();
					    	  payment.setAmount(amount);
					    	  payment.setPaymentDate(paymentdate);;
					    	  payment.setId(id);
					    	  payment.setInvoiceId(invoiceId);
					    	  payment.setProductId(productId);
					    	  payment.setStatus(status);
					    	  paymentList.add(payment);
					      }
					      if("RESULT".equalsIgnoreCase(name)) {
					    	  result = element2.getText();
					      }
					    }
					    List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
					    if(!result.equals("0")) {
					    	if(result.equals("1")) {
					    		jsonStr = JSON.toJSONString(monthlyBillErrorList);
					    	}
					    	else {
					    		MonthlyBillError monthlyBillError = new MonthlyBillError();
						    	monthlyBillError.setCode(result);
						    	monthlyBillError.setMessage("");
						    	monthlyBillError.setReason("");
						    	monthlyBillError.setReferenceError("");
						    	monthlyBillErrorList.add(monthlyBillError);
						    	jsonStr = JSON.toJSONString(monthlyBillErrorList);
					    	}
					    	
					    }
					    else {
						    _log.info("=======================resp111========================"+resp);
						    jsonStr = JSON.toJSONString(paymentList);
						    _log.info("=======================respXMLJSON========================");
						    _log.info("---返回的消息---"+jsonStr);
						    _log.info("=======================respXML========================");
					    }
				}
				else {
					List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
					MonthlyBillError monthlyBillError = new MonthlyBillError();
			    	monthlyBillError.setCode(result);
			    	monthlyBillError.setMessage("");
			    	monthlyBillError.setReason("");
			    	monthlyBillError.setReferenceError("");
			    	monthlyBillErrorList.add(monthlyBillError);
			    	jsonStr = JSON.toJSONString(monthlyBillErrorList);
				}
                //记录消息到日志表
                LogUtil.saveLogToABM_TMall(request,result,startTime);

				byte[] resps = jsonStr.getBytes("UTF-8");
				body.write(resps);
				body.close();
			}
			else if(requestPath.endsWith(MonthlyBill)){
				//账单API
				_log.info("start MonthlyBill......");
				
				String serialNumber = request.getParameter("serialNumber") == null ? "": request.getParameter("serialNumber");
				String lanId = request.getParameter("lanId") == null ? "": request.getParameter("lanId");
				String resultLanIdStr = lanId.substring(0, 5);
				StringBuilder buildStringMes = new StringBuilder();
				String webserviceUrl = getURLForJf3( resultLanIdStr,IS_WUHAN);//获取URL地址
				String urlForJf4 = getURLForJf4( resultLanIdStr,IS_WUHAN);//0旧的 1新的
				if("1".equals(urlForJf4)) {
					//新接口新域名
					buildStringMes.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.asiainfo.com/\">\r\n" + 
							"   <soapenv:Header/>\r\n" + 
							"   <soapenv:Body>\r\n" + 
							"      <web:queryEInvoice>\r\n" + 
							"         <QueryEInvoiceRequest>\r\n" + 
							"            <lanId>"+lanId+"</lanId>\r\n" + 
							"            <serialNumber>"+serialNumber+"</serialNumber>\r\n" + 
							"            <apiType>"+1+"</apiType>\r\n" + 
							"         </QueryEInvoiceRequest>\r\n" + 
							"      </web:queryEInvoice>\r\n" + 
							"   </soapenv:Body>\r\n" + 
							"</soapenv:Envelope>");
				}else {
					buildStringMes.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.hquery.ailk.com/\">");
					buildStringMes.append("<soapenv:Header/>");
					buildStringMes.append("<soapenv:Body>");
					buildStringMes.append("<m:QueryEInvoiceRequest xmlns:m=\"http://ygz.service.boss/client/\">");
					buildStringMes.append("<m:lanId>"+lanId+"</m:lanId>");
					buildStringMes.append("<m:serialNumber>"+serialNumber+"</m:serialNumber>");
					buildStringMes.append("<m:apiType>"+1+"</m:apiType>");
					buildStringMes.append("</m:QueryEInvoiceRequest>");
					buildStringMes.append("</soapenv:Body>");
					buildStringMes.append("</soapenv:Envelope>");
				}
				
				List<com.hp.bon.sgw.wh.bean.MonthlyBill> monthlyBillList = new ArrayList<com.hp.bon.sgw.wh.bean.MonthlyBill>();
				String resp =  StringEscapeUtils.unescapeXml(getWebserviceStr(buildStringMes, webserviceUrl));
				String result = "";
				String jsonStr = "";
			    response.set("X-CTG-Request-ID", value);
			    response.set("X-RateLimit-Limit", "60");
			    response.set("X-RateLimit-Remaining", "48");
			    response.set("X-RateLimit-Reset", "14");
                resp=resp.replace("<ITEM/>","");
				if(!resp.equals("")) {
					    _log.info("=======================resp========================"+resp);
					    Document doc = null;
					    doc = DocumentHelper.parseText(resp);
					    Element node = doc.getRootElement();
					    List<Element> element = getElement(node);
					    for (int j = 0; j < element.size(); j++) {
					      Element element2 = element.get(j);
					      String name = element2.getName();
					      if ("ITEM".equalsIgnoreCase(name)) {
					    	  com.hp.bon.sgw.wh.bean.MonthlyBill monthlyBill = new com.hp.bon.sgw.wh.bean.MonthlyBill();
					    	  _log.info("=======================1111========================");
					    	  String id = element2.element("ID").getText();
					    	  _log.info("=======================id========================"+id);
					    	  String productId = element2.element("productId").getText();
					    	  String billMonth = element2.element("billMonth").getText();
					    	  String amount = element2.element("amount").getText();
					    	  String invoiceId = element2.element("invoiceId").getText();
					    	  String status = element2.element("Status") == null ?element2.element("status").getText() : element2.element("Status").getText();
					    	  monthlyBill.setAmount(amount);
					    	  monthlyBill.setBillMonth(billMonth);
					    	  monthlyBill.setId(id);
					    	  monthlyBill.setInvoiceId(invoiceId);
					    	  monthlyBill.setProductId(productId);
					    	  monthlyBill.setStatus(status);
					    	  monthlyBillList.add(monthlyBill);
					      }
					      if("RESULT".equalsIgnoreCase(name)) {
					    	  result = element2.getText();
					      }
					    }
					    List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
					    if(!result.equals("0")) {
					    	if(result.equals("1")) {
					    		jsonStr = JSON.toJSONString(monthlyBillErrorList);
					    	}
					    	else {
					    		MonthlyBillError monthlyBillError = new MonthlyBillError();
						    	monthlyBillError.setCode(result);
						    	monthlyBillError.setMessage("");
						    	monthlyBillError.setReason("");
						    	monthlyBillError.setReferenceError("");
						    	monthlyBillErrorList.add(monthlyBillError);
						    	jsonStr = JSON.toJSONString(monthlyBillErrorList);
					    	}
					    	
					    }
					    else {
						    _log.info("=======================resp111========================"+resp);
						    jsonStr = JSON.toJSONString(monthlyBillList);
						    _log.info("=======================respXMLJSON========================");
						    _log.info("---返回的消息---"+jsonStr);
						    _log.info("=======================respXML========================");
					    }
				}
				else {
					List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
					MonthlyBillError monthlyBillError = new MonthlyBillError();
			    	monthlyBillError.setCode(result);
			    	monthlyBillError.setMessage("");
			    	monthlyBillError.setReason("");
			    	monthlyBillError.setReferenceError("");
			    	monthlyBillErrorList.add(monthlyBillError);
			    	jsonStr = JSON.toJSONString(monthlyBillErrorList);
				}
				//记录消息到日志表
                LogUtil.saveLogToABM_TMall(request,result,startTime);

				byte[] resps = jsonStr.getBytes("UTF-8");
				body.write(resps);
				body.close();
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			_log.warn("",e);
			errorAck(body, "", "", STATUS_FAIL, "9999", "do business fail");
            //记录消息到日志表
            TaskManager.taskProcess(null);
			return;
		}
//        TaskManager.taskProcess(null);

		try {
			BIZTYPETEMP = request.getParameter("bizType") == null ? "" : request.getParameter("bizType");
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		if (requestPath.endsWith(TaobaoPay))//充值地址
		{
			TaobaoPayRequestBean beanTaobaoPayReqBean = TaobaoPayRequestUtil.getReqParams(request);
			String tbOrderNo  = beanTaobaoPayReqBean.getTbOrderNo();
			String bizType =  beanTaobaoPayReqBean.getBizType();
			String spuId =  beanTaobaoPayReqBean.getSpuId();
			String accountVal =  beanTaobaoPayReqBean.getAccountVal();
			String supplierId =  beanTaobaoPayReqBean.getSupplierId();
			String timeStart =  beanTaobaoPayReqBean.getTimeStart();
			String timeLimit =  beanTaobaoPayReqBean.getTimeLimit();
			String buyNum =  beanTaobaoPayReqBean.getBuyNum();
			String unitPrice =  beanTaobaoPayReqBean.getUnitPrice();
			String totalPrice =  beanTaobaoPayReqBean.getTotalPrice();
			String tbPrice =  beanTaobaoPayReqBean.getTbPrice();
			String buyerId =  beanTaobaoPayReqBean.getBuyerId();
			String sellerId =  beanTaobaoPayReqBean.getSellerId();
			String buyerIp =  beanTaobaoPayReqBean.getBuyerIp();
			String notifyUrl =  beanTaobaoPayReqBean.getNotifyUrl();
			String ts =  beanTaobaoPayReqBean.getTs();
			String sign =  beanTaobaoPayReqBean.getSign();
				//bizType值为FIXEDLINE,NETWORK,其他值，则业务为固话宽带充值(查询)；
				String taobaoBankCode = whConfigService.getValue(AliParam.taobaoBankCode, "");
				String taobaopubKeyValue = whConfigService.getValue(AliParam.taobaoPubKeyValue, "");
				try {
					_log.info("start TaobaoPay:FIXEDLINE,NETWORK,other");
					if( !TaobaoPayRequestUtil.checkReqWithNotEmpty(beanTaobaoPayReqBean) ){
						errorAck1(body, bizType, tbOrderNo, tbOrderNo,REQUEST_FAIL, "0101", "");
						return;
					}
					if (!taobao_supplierId.equals(supplierId)) {
						_log.error("taobao_supplierId ={} is not equals supplierId ={}",taobao_supplierId,supplierId);
						errorAck1(body, bizType, tbOrderNo, tbOrderNo,REQUEST_FAIL, "0102", "");
						return;
					}
					long time = System.currentTimeMillis();
					long tsLong = Long.valueOf(ts);
					//单位秒
                    int ts_check = userResourceConfigService.getIntValue("ts_check",0);

                    if ((tsLong + ts_check*1000) < time) {
						_log.error("tsLong + interval) < time");
						errorAck1(body, bizType, tbOrderNo, tbOrderNo,REQUEST_FAIL, "0104", "");
						return;
					}
					int intCardNum = 0;
					try {
						intCardNum = Integer.parseInt(buyNum);
						if (spuIdMap.get(spuId) == null) {
							_log.warn("spuId 在配置文件中未发现，spuId = {}", spuId);
							errorAck1(body, bizType, tbOrderNo, tbOrderNo, STATUS_FAIL, "0204", "");
							return;
						}
					} catch (Exception e) {
						_log.error(" parseInt buyNum ={} is Exception ={}",buyNum,e.getMessage());
						errorAck1(body, bizType, tbOrderNo, tbOrderNo, STATUS_FAIL, "0401", "");
						return;
					}
					if (spuIdBalanceMap.get(spuId) == null) {
						_log.error("spuIdBalanceMap 在配置文件中未发现，spuId = {}", spuId);
						errorAck1(body, bizType, tbOrderNo, tbOrderNo, STATUS_FAIL, "0204", "");
						return;
					}
					if (!unitPrice.equals(spuIdMap.get(spuId) + "")) {
						_log.error("spuIdMap 在配置文件中未发现，spuId = {}", spuId);
						errorAck1(body, bizType, tbOrderNo, tbOrderNo, REQUEST_FAIL, "9999", "");
						return;
					}
					if (!totalPrice.equals(intCardNum * spuIdMap.get(spuId) + "")) {
						_log.error("spuIdMap 在配置文件中未发现，spuId = {}, totalPrice ={}", spuId,totalPrice);
						errorAck1(body, bizType, tbOrderNo, tbOrderNo, REQUEST_FAIL, "9999", "");
						return;
					}
					String[] accountVals = accountVal.split("-");
					FixedBroadbandBean fixedBroadbandBean = new FixedBroadbandBean(
							tbOrderNo, bizType, spuId, accountVal, supplierId,
							timeStart, timeLimit, buyNum, unitPrice,
							totalPrice, tbPrice, buyerId, sellerId, buyerIp,
							notifyUrl, ts, sign);
					// 验证签名
					_log.info("pubkeyValue = {}", pubKeyValue);
					_log.info("String = {}", fixedBroadbandBean.toString());
					_log.info("sign = {}", sign);
					String source = TaobaoPayRequestUtil.createSource(request);
					String md5Sign = source + taobaopubKeyValue;
					if (!SignUtilsImpl.checkTmallSign(md5Sign, sign)) {
						_log.error("checkTmallSign is not pass");
						errorAck1(body, bizType, tbOrderNo, tbOrderNo,REQUEST_FAIL, "0102", "");
						return;
					}
//					String scid_ = "Recharge.SGW@027.ctnbc-bon.net";
                    //提前配置鉴权
                    String _payment_Amount2 = intCardNum * spuIdBalanceMap.get(spuId) + "";
                    com.alibaba.fastjson.JSONObject jsonObject=new com.alibaba.fastjson.JSONObject();
                    jsonObject.put("accountVal",accountVal);
                    jsonObject.put("buyerIp",buyerIp);
                    jsonObject.put("accountVals",accountVals);
                    jsonObject.put("taobaoBankCode",taobaoBankCode);
                    jsonObject.put("tbOrderNo",tbOrderNo);
                    jsonObject.put("totalPrice",totalPrice);
                    jsonObject.put("_payment_Amount2",_payment_Amount2);

                    String scid_ = "ServAuth.jf3@027.ctnbc-bon.net";
                    String _payment_Amount = intCardNum * spuIdBalanceMap.get(spuId) + "";
                    String tmallHostId =  whConfigService.getValue(AliParam.taobaoHostId,"Alibaba1@027.ctnbc-bon.net");
                    String sessionId = DiameterUtils.makeSessionID(tmallHostId);
                    XmlMessage req = TaobaoPayRequestUtil.createReqAAA(accountVal, tmallHostId, sessionId, buyerIp, receiveTime,
                            scid_, accountVals, taobaoBankCode, tbOrderNo, totalPrice, _payment_Amount);

                    // new CallParam对象
					FixedBroadbandHandler tmallPayHandle = new FixedBroadbandHandler(
							body, fixedBroadbandBean, tmallResponseService,
							asynExecutor, taobaopubKeyValue, jsonObject);
					CallParam callParam = new CallParam(req.getMID(),req.getSCID(), req, req.getUID(), tmallPayHandle);
					BuzProcessorManager.getInstance().processRequest(callParam);
				} catch (Exception e) {
					e.printStackTrace();
					_log.error("请求过程异常",e);
					errorAck1(body, bizType, tbOrderNo, tbOrderNo, STATUS_FAIL,"0401", "");
					return;
				}
		} else if (requestPath.endsWith(TaobaoQuery)){
			// 订单查询
				_log.info("start TaobaoQuery......");
				String tbOrderNo = null;
				String bizType = null;
				try {
					String ts = request.getParameter("ts") == null ? "" : request.getParameter("ts");
					tbOrderNo = request.getParameter("tbOrderNo") == null ? "" : request.getParameter("tbOrderNo");
					bizType = request.getParameter("bizType") == null ? "" : request.getParameter("bizType");
					String supplierId = request.getParameter("supplierId") == null ? "" : request.getParameter("supplierId");
					String sign = request.getParameter("sign") == null ? "" : request.getParameter("sign");
					if (ts.equals("") || tbOrderNo.equals("") || sign.equals("") || supplierId.equals("") || bizType.equals("")) {
						_log.error("Req's params is null");
						errorAck1(body, bizType, tbOrderNo, tbOrderNo, REQUEST_FAIL, "0101", "");
						return;
					}
					if (!taobao_supplierId.equals(supplierId)) {
						_log.error("taobao_supplierId ={} is not equals supplierId ={}",taobao_supplierId,supplierId);
						errorAck1(body, bizType, tbOrderNo, tbOrderNo, REQUEST_FAIL, "0102", "");
						return;
					}
					long time = System.currentTimeMillis();
					long tsLong = Long.valueOf(ts);
//					long interval = 24 * 60 * 60 * 1000;
                    //单位秒
                    int ts_check = userResourceConfigService.getIntValue("ts_check",0);
					if ((tsLong + ts_check*1000) < time) {
						_log.error("(tsLong + interval) < time");
						errorAck1(body, bizType, tbOrderNo, tbOrderNo, STATUS_TS_EXPIRED, "0104", "");
						return;
					}
					FixedBroadOrderBean fixedBroadOrderBean = new FixedBroadOrderBean(tbOrderNo, sign, bizType, supplierId, ts);
					// 验证签名
					String pubKey = whConfigService.getValue(AliParam.taobaoPubKeyValue, "");
					String md5Sign = fixedBroadOrderBean.toString() + pubKey;
					if (!SignUtilsImpl.checkTmallSign(md5Sign, sign)) {
						_log.error("checkTmallSign is not pass...");
						errorAck1(body, bizType, tbOrderNo, tbOrderNo,REQUEST_FAIL, "0102", "");
						return;
					}
							Element serviceInformation = DocumentHelper.createElement("Service_Information");
                            Element element = serviceInformation.addElement("Channel_Id");
                            element.setText("200");
                            element = serviceInformation.addElement("Bank_code");
//                            String bankCode=whConfigService.getValue("taobao.bankCode","");
                            element.setText(bankCode);
                            element = serviceInformation.addElement("Serial_Type");
                            element.setText("0");
                            tbOrderNo = request.getParameter("tbOrderNo") == null ? "" : request.getParameter("tbOrderNo");
                            element = serviceInformation.addElement("Payment_Serial_Nbr");
                            element.setText(tbOrderNo);

							XmlMessage req = new XmlMessage(true);
							String tmallHostId = whConfigService.getValue(AliParam.tmallHostId,"Alibaba1@27.ctnbc-bon.net");
							String sessionId = DiameterUtils.makeSessionID(tmallHostId);
							req.setIp(IP);
							req.setMsgTime(receiveTime);
							req.setMID(sessionId);
							req.setUID(tmallHostId);
//							req.setSCID("Recharged-Query.SGW@027.ctnbc-bon.net");
                            req.setSCID("RechargeQuery.jf3@027.ctnbc-bon.net");
                            req.setSIG(null);
							req.setREPTAG(0);
							req.setDATA(serviceInformation.asXML());
							req.setDataElement(serviceInformation);
							FixedBroadOrderQueryHandle tmallOrderCancelHandler = new FixedBroadOrderQueryHandle(body, fixedBroadOrderBean, tmallResponseService,asynExecutor,tmallRetUrl,pubKeyValue);
							CallParam callParam = new CallParam(req.getMID(), req.getSCID(),req, req.getUID(), tmallOrderCancelHandler);
 							BuzProcessorManager.getInstance().processRequest(callParam);
				} catch (Exception e) {
					_log.warn("start TaobaoQuery is error,msg ={}",e.getMessage());
					_log.error("",e);
					errorAck1(body, bizType, tbOrderNo, tbOrderNo,REQUEST_FAIL, "9999", "");
					return;
				}
		} else if (requestPath.endsWith(PointExchange)) {
			// 积分兑换
			//2.2.3.2天翼商城积分兑换话费充值
			String Acc_Nbr = null;
			String Payment_Serial_Nbr = null;
			try {
				_log.info("start PointExchange......"+PointExchange);

				String Area_code = request.getParameter("Area_code") == null ? "" : request.getParameter("Area_code");
				String DestinationAttr = request .getParameter("DestinationAttr") == null ? "" : request .getParameter("DestinationAttr");
				Acc_Nbr = request.getParameter("Acc_Nbr") == null ? "" : request.getParameter("Acc_Nbr");
				Payment_Serial_Nbr = request.getParameter("Payment_Serial_Nbr") == null ? "" : request.getParameter("Payment_Serial_Nbr");
				String ProductId = request.getParameter("ProductId") == null ? "" : request.getParameter("ProductId");
				String ProductName = request.getParameter("ProductName") == null ? "" : request.getParameter("ProductName");
				String Channel_Id = request.getParameter("Channel_Id") == null ? "" : request.getParameter("Channel_Id");
				String Bank_code = request.getParameter("Bank_code") == null ? "" : request.getParameter("Bank_code");
				String cityId = request.getParameter("cityId") == null ? "" : request.getParameter("cityId");
				if (Area_code.equals("") || DestinationAttr.equals("")
						|| Acc_Nbr.equals("") || Payment_Serial_Nbr.equals("")
						|| ProductId.equals("") || ProductName.equals("")
						|| Channel_Id.equals("") || Bank_code.equals("")
						|| cityId.equals("")) {
					errorAck2(body, "-1", "参数错误", Acc_Nbr, Payment_Serial_Nbr,
							"", "");
					return;
				}

				if (ProductIdMap.get(ProductId) == null) {
					_log.warn("ProductId 在配置文件中未发现，ProductIdMap = {}",
							ProductId);
					errorAck2(body, "-1", "ProductId错误", Acc_Nbr,
							Payment_Serial_Nbr, "", "");
					return;
				}

				if (AmountMap.get(ProductId) == null) {
					_log.warn("ProductId 在配置文件中未发现，AmountMap = {}", ProductId);
					errorAck2(body, "-1", "ProductId错误", Acc_Nbr,
							Payment_Serial_Nbr, "", "");
					return;
				}

				PointExchangeBean pointExchangeBean = new PointExchangeBean(
						Area_code, DestinationAttr, Acc_Nbr,
						Payment_Serial_Nbr, ProductId, ProductName, Channel_Id,
						Bank_code, ProductIdMap.get(ProductId), cityId);
				// 验证签名
				_log.info("pubkeyValue = {}", pubKeyValue);
				_log.info("String = {}", pointExchangeBean.toString());
				String md5Sign = pointExchangeBean.toString() + pubKeyValue;

				Element root = DocumentHelper.createElement("root");

                //2019-12-19改造
                Element element = root.addElement("cityId");
                element.setText(cityId);
                element = root.addElement("transactionID");
                element.setText(Payment_Serial_Nbr);
                element = root.addElement("number");
                element.setText(Acc_Nbr);
                // Payment_Serial_Nbr
                element = root.addElement("serviceId");
                element.setText(ProductId);
                element = root.addElement("serviceName");
                element.setText(ProductName);
                element = root.addElement("costIntegral");
                element.setText(ProductIdMap.get(ProductId) + "");
                element = root.addElement("channelType");
                element.setText("46");
                element = root.addElement("numberType");
                element.setText("12");
                element = root.addElement("requestTime");
                element.setText(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
                element = root.addElement("orderNbr");
                element.setText(Payment_Serial_Nbr);
				String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
						+ root.asXML();
				_log.info("报文:" + s);
				_log.info("地址:" + pointExchange_url);
				String reslut = (String) getServiceClient(pointExchange_url)
						.invoke(new Object[] { s });// 调用后台webservice服务
				_log.info("returnXML:" + reslut);

				Map<String, Object> data = xmlStrToMap(reslut);
				_log.info("报文:" + data.toString());
				if ("0000".equals(data.get("returnCode"))) {
				    //成功
					Element Service_Information = DocumentHelper.createElement("Service_Information");
					String city_code_new=getAreaCode(cityId);
					String versionType = getVersionType(cityId,"0");//传参0 1001类 传1 84210类   返参 1 新 0 旧的
					if("1".equals(versionType)) {
						// 新流程
						element = Service_Information.addElement("Channel_Id");
						element.setText("200");
//						element = Service_Information.addElement("Acc_Nbr");
//						element.setText(Acc_Nbr);
						element = Service_Information.addElement("Area_Code");
						element.setText(city_code_new);
						element = Service_Information.addElement("DestinationAttr");
						element.setText(DestinationAttr);
						element = Service_Information.addElement("Destination_Id");
						element.setText(Acc_Nbr);
						element = Service_Information.addElement("Destination_Id_Type");
						element.setText("2");
						element = Service_Information.addElement("Payment_Amount");
						element.setText(AmountMap.get(ProductId) + "");
						element = Service_Information.addElement("RequestAmount");
						element.setText("0");
						element = Service_Information.addElement("Payment_Method");
						element.setText("11");
						element = Service_Information.addElement("Paid_Time");
						element.setText(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
						element = Service_Information.addElement("Payment_Serial_Nbr");
						element.setText(Payment_Serial_Nbr);
						element = Service_Information.addElement("Balance_Type");
//                        String flag=userResourceConfigService.getValue("jf3_flag","0");
//						if("0".equals(flag)){
//                            if (cityId.equals("1001")) {
//							    element.setText("12313");
//						     } else {
//							    element.setText("302744");
//                            }
//                        }else if("1".equals(flag)&&cityId.equals("1001")){
//                            element.setText("12313");
//                        }else{
//                            element.setText("302744");
//                        }
						if (cityId.equals("1001")) {
							element.setText("12313");
						} else {
							element.setText("302744");
						}
						element = Service_Information.addElement("Eff_Date");
						element.setText(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
						element = Service_Information.addElement("Exp_Date");
						element.setText("20371221235959");
						element = Service_Information.addElement("Bonus_Rows");
						element.setText("0");
						element = Service_Information.addElement("Bank_code");
						element.setText("WX_01");
					}else {

						//旧的
						element = Service_Information.addElement("Acc_Nbr");
						element.setText(Acc_Nbr);
						element = Service_Information.addElement("BillQuery_Type");
						element.setText("2");
						element = Service_Information.addElement("CHARGE_FLAG");
						element.setText("0");
						element = Service_Information.addElement("BALANCETYPEID");
						if (cityId.equals("1001")) {
							element.setText("12313");
						} else {
							element.setText("302744");
						}
						element = Service_Information.addElement("Destination_Balance_Unit");
						element.setText("0");
						element = Service_Information.addElement("StartTime");
						element.setText(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
						element = Service_Information.addElement("EndTime");
						element.setText("20371221235959");
						element = Service_Information.addElement("STAFF");
						element.setText("");
						element = Service_Information.addElement("ORGID");
						element.setText("");
						element = Service_Information.addElement("StateDate");
						element.setText(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
						element = Service_Information.addElement("Destination_Attr");
						element.setText("2");
						element = Service_Information.addElement("Area_Code");
						element.setText("027");
						element = Service_Information.addElement("Bank_code");
						element.setText(Bank_code);
						element = Service_Information.addElement("Payment_Serial_Nbr");
						element.setText(Payment_Serial_Nbr);
						element = Service_Information.addElement("Payment_Amount");
						element.setText(AmountMap.get(ProductId) + "");
					}


					XmlMessage req = new XmlMessage(true);
					String tmallHostId = "EpoingMall@027.ctnbc-bon.net";
					String sessionId = DiameterUtils.makeSessionID(tmallHostId);
					req.setIp(IP);
					req.setMsgTime(receiveTime);
					req.setMID(sessionId);
					req.setUID(tmallHostId);
					req.setSCID("1".equals(versionType) ? "Recharged.jf3@027.ctnbc-bon.net" : "SeverRecharge.SGWPAY@027.ctnbc-bon.net");//判断走新旧流程,走不同的DCC
					req.setSIG(null);
					req.setREPTAG(0);
					req.setDATA(Service_Information.asXML());
					req.setDataElement(Service_Information);
					_log.info("报文:" + data.get("surplusPoint").toString());
					// new CallParam对象
					PointExchangeHandler pointExchangeHandler = new PointExchangeHandler(
							body, pointExchangeBean, tmallResponseService,
							asynExecutor, pubKeyValue, rollbackExchange_url,
							data.get("surplusPoint").toString(),
							ProductIdMap.get(ProductId) + "",
							getServiceClientForBack(pointExchange_url));
					CallParam callParam = new CallParam(req.getMID(),
							req.getSCID(), req, req.getUID(),
							pointExchangeHandler);
					BuzProcessorManager.getInstance().processRequest(callParam);
				} else {
					errorAck2(body, data.get("returnCode").toString(), data
							.get("returnMessage").toString(), Acc_Nbr,
							Payment_Serial_Nbr, "", "");
					return;
				}
			} catch (Exception e) {
				_log.info("异常",e);
				errorAck2(body, "-1", "兑换话费失败", Acc_Nbr, Payment_Serial_Nbr,
						"", "");
				return;
			}
		} else if (requestPath.endsWith(NetListQuery))// 集团电渠历史账单
		{

			_log.info("start NetListQuery");
			try {
				BufferedReader in = new BufferedReader(new InputStreamReader(
						request.getInputStream()));
				StringBuilder stb = new StringBuilder();
				String line = null;
				while ((line = in.readLine()) != null) {
					stb.append(line);
				}
				_log.info("报文:" + stb.toString());
				Map<String, Object> data = queryXml(stb.toString());
				_log.info("报文:" + data.toString());
				Element Service_Information = DocumentHelper
						.createElement("Service_Information");
				if ("SVC81011".equals(data.get("ServiceCode"))) {// 详单
					Element valueType = Service_Information
							.addElement("ValueType");
					valueType.setText("1");
					Element element = Service_Information.addElement("Value");
					element.setText(data.get("CustMobile").toString());
					element = Service_Information.addElement("Area_Code");
					if (data.get("AreaCode") != null
							&& !"".equals(data.get("AreaCode").toString())) {
						element.setText(data.get("AreaCode").toString());
					} else {
						element.setText("");
					}
					element = Service_Information.addElement("QueryType");
					element.setText("1");

					_log.info("Service_Information："
							+ Service_Information.asXML());
					_log.info("Service_Information 拼装结束");

					XmlMessage req = new XmlMessage(true);
					String HostId = "jtqz@027.ctnbc-bon.net";
					String sessionId = DiameterUtils.makeSessionID(HostId);
					req.setIp(IP);
					req.setMsgTime(receiveTime);
					req.setMID(sessionId);
					req.setUID(HostId);
					req.setSCID("QueryServ.HSS_TB@027.ctnbc-bon.net");
					req.setSIG(null);
					req.setREPTAG(0);
					req.setDATA(Service_Information.asXML());
					req.setDataElement(Service_Information);
					_log.info("拼装:" + req.toString());
					// new CallParam对象
					NetListQueryHandler pointExchangeHandler = new NetListQueryHandler(
							body, data, tmallResponseService, asynExecutor,
							netListQuery_url);
					CallParam callParam = new CallParam(req.getMID(),
							req.getSCID(), req, req.getUID(),
							pointExchangeHandler);
					BuzProcessorManager.getInstance().processRequest(callParam);
				}/*
				 * else if("SVC81005".equals(data.get("ServiceCode"))){//账单
				 * Element Service_Information =
				 * DocumentHelper.createElement("Service_Information"); Element
				 * bill_Information =
				 * Service_Information.addElement("Bill_Information");
				 * 
				 * Element element = bill_Information.addElement("Acc_Nbr");
				 * if(data.get("MobileType")!=null &&
				 * "1".equals(data.get("MobileType").toString())){
				 * element.setText(data.get("CustMobile").toString());
				 * _log.info("CustMobile:"+data.get("CustMobile").toString());
				 * }else{
				 * element.setText(data.get("AreaCode").toString()+data.get
				 * ("CustMobile").toString());
				 * _log.info("AreaCode_CustMobile:"+data
				 * .get("AreaCode").toString
				 * ()+"_"+data.get("CustMobile").toString()); } element =
				 * bill_Information.addElement("DestinationAttr");
				 * if(data.get("MobileType")!=null &&
				 * "1".equals(data.get("MobileType").toString())){
				 * element.setText("2"); }else if(data.get("MobileType")!=null
				 * && "2".equals(data.get("MobileType").toString())){
				 * element.setText("0"); }else if(data.get("MobileType")!=null
				 * && "3".equals(data.get("MobileType").toString())){
				 * element.setText("3"); }
				 * 
				 * element = bill_Information.addElement("Billing_Cycle");
				 * element.setText(data.get("Month").toString());
				 * _log.info("Month:"+data.get("Month").toString()); element =
				 * bill_Information.addElement("Query_Flag");
				 * element.setText(data.get("QueryType").toString());
				 * _log.info("QueryType:"+data.get("QueryType").toString());
				 * 
				 * element = bill_Information.addElement("QueryType");
				 * element.setText("1");
				 * 
				 * _log.info("Service_Information："+Service_Information.asXML());
				 * _log.info("Service_Information 拼装结束");
				 * 
				 * XmlMessage req = new XmlMessage(true); String HostId =
				 * "jtqz@027.ctnbc-bon.net"; String sessionId =
				 * DiameterUtils.makeSessionID(HostId); req.setIp(IP);
				 * req.setMsgTime(receiveTime); req.setMID(sessionId);
				 * req.setUID(HostId);
				 * req.setSCID("BillDetailQuery.BillYXHB9@027.ctnbc-bon.net");
				 * req.setSIG(null); req.setREPTAG(0);
				 * req.setDATA(Service_Information.asXML());
				 * req.setDataElement(Service_Information);
				 * _log.info("拼装:"+req.toString()); // new CallParam对象
				 * BillListQueryHandler billHandler = new
				 * BillListQueryHandler(body, data, tmallResponseService,
				 * asynExecutor); CallParam callParam = new
				 * CallParam(req.getMID(), req.getSCID(),req, req.getUID(),
				 * billHandler);
				 * BuzProcessorManager.getInstance().processRequest(callParam);
				 * }
				 */
				else {
					XmlMessage req = new XmlMessage(true);
					String HostId = "jtqz@027.ctnbc-bon.net";
					String sessionId = DiameterUtils.makeSessionID(HostId);
					req.setIp(IP);
					req.setMsgTime(receiveTime);
					req.setMID(sessionId);
					req.setUID(HostId);
					req.setSCID("QueryServ.HSS_TB@027.ctnbc-bon.net");
					req.setSIG(null);
					req.setREPTAG(0);
					req.setDATA(Service_Information.asXML());
					req.setDataElement(Service_Information);
					NetListQueryHandler pointExchangeHandler = new NetListQueryHandler(
							body, data, tmallResponseService, asynExecutor,
							netListQuery_url);
					CallParam callParam = new CallParam(req.getMID(),
							req.getSCID(), req, req.getUID(),
							pointExchangeHandler);
					BuzProcessorManager.getInstance().processRequest(callParam);
				}

			} catch (Exception e) {
				e.printStackTrace();
				_log.info("异常" + e.getMessage());
				return;
			}
		}
	}

	private static String getWebserviceStr(StringBuilder buildStringMes,String webserviceUrl) {
		_log.info("===========webservice url==============="+webserviceUrl);
		String resp = "";
		_log.info("===========webservice url==============="+webserviceUrl);
		PostMethod post = new PostMethod(webserviceUrl);
		post.setRequestHeader("SOAPAction", "");
		try {
			RequestEntity requestEntity = new StringRequestEntity(buildStringMes.toString(), "text/xml", "UTF-8");
			post.setRequestEntity(requestEntity);
			HttpClient client = new HttpClient();
			
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5*1000);
			try {
				client.executeMethod(post);
			} catch (HttpException e) {
				_log.info("===========webservice call timeout==============="+webserviceUrl);
				return "";
			} catch (IOException e) {
				_log.info("===========webservice call timeout session_id:");
				return "";
			}
			try {
				_log.info("===========完成webservice==============="+resp);
				InputStream str = post.getResponseBodyAsStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(str));
				StringBuffer stringBuffer = new StringBuffer();
				String result = "";
				while((result = br.readLine()) != null) {
					stringBuffer.append(result);
				}
				resp = stringBuffer.toString();
				//resp = post.getResponseBodyAsString();
			} catch (IOException e) {
				_log.info("===========webservice call timeout==============="+webserviceUrl);
				return "";
			}
		} catch (UnsupportedEncodingException e) {
			_log.info("===========webservice call timeout==============="+webserviceUrl);
			e.printStackTrace();
		}
		return resp;
	}
	

	private static Call getServiceClient(String serverURL) throws Exception {
		Call call = null;
		try {
			Service service = new Service();
			call = (Call) service.createCall();
			call.setTimeout(new Integer(30 * 1000));// 设置访问后台webservice服务的超时时间2秒,2秒后自动断开
			call.setTargetEndpointAddress(new URL(serverURL));// 设置webservice服务的url地址
			call.setOperationName(new QName(serverURL, "PointExchange_BSS3"));// 调用的后台webservice服务的方法为exchange
            _log.info("=====请求URL:{} 方法名service:{}",serverURL,"PointExchange_BSS3");
		} catch (Exception e) {
			_log.info("异常" + e.getMessage());
		}
		return call;
	}

	private static Call getServiceClientForBack(String serverURL)
			throws Exception {
		Call call = null;
		try {
			Service service = new Service();
			call = (Call) service.createCall();
			call.setTimeout(new Integer(30 * 1000));// 设置访问后台webservice服务的超时时间2秒,2秒后自动断开
			call.setTargetEndpointAddress(new URL(serverURL));// 设置webservice服务的url地址
			call.setOperationName(new QName(serverURL, "RollBackExchange_BSS3"));
            _log.info("=====请求URL:{} 方法名service:{}",serverURL,"RollBackExchange_BSS3");
		} catch (Exception e) {
			_log.info("异常" + e.getMessage());
		}
		return call;
	}

	private static Call callCSB(String serverURL) throws Exception {
		Call call = null;
		try {
			Service service = new Service();
			call = (Call) service.createCall();
			call.setTimeout(new Integer(30 * 1000));// 设置访问后台webservice服务的超时时间2秒,2秒后自动断开
			call.setTargetEndpointAddress(new URL(serverURL));// 设置webservice服务的url地址
			call.setOperationName(new QName("http://access.hbgz.com",
					"capacityService"));
		} catch (Exception e) {
			_log.info("异常" + e.getMessage());
		}
		return call;
	}

	private static Call call(String serverURL) throws Exception {
		Call call = null;
		try {
			Service service = new Service();
			call = (Call) service.createCall();
			call.setTimeout(new Integer(30 * 1000));// 设置访问后台webservice服务的超时时间2秒,2秒后自动断开
			call.setTargetEndpointAddress(new URL(serverURL));// 设置webservice服务的url地址
			call.setOperationName(new QName("http://access.hbgz.com",
					"capacityService"));// 调用的后台webservice服务的方法为exchange
		} catch (Exception e) {
			_log.info("异常" + e.getMessage());
		}
		return call;
	}

	/**
	 * 将xml格式的字符串转换成Map对象
	 * 
	 * @param xmlStr
	 *            xml格式的字符串
	 * @return Map对象
	 * @throws Exception
	 *             异常
	 */
	public static Map<String, Object> queryXml(String xmlStr) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		// 将xml格式的字符串转换成Document对象
		Document doc = DocumentHelper.parseText(xmlStr);
		// 获取根节点
		Element root = doc.getRootElement();
		// 获取根节点下的所有元素
		List children = root.elements();
		// 循环所有子元素
		if (children != null && children.size() > 0) {
			for (int i = 0; i < children.size(); i++) {
				Element child = (Element) children.get(i);
				map.put(child.getName(), child.getTextTrim());
				System.out.println(child.getName() + ":" + child.getTextTrim());
				for (int j = 0; j < child.elements().size(); j++) {
					Element child1 = (Element) child.elements().get(j);
					map.put(child1.getName(), child1.getTextTrim());
					_log.info(child1.getName() + ":" + child1.getTextTrim());
				}
			}
		}
		return map;
	}

	/**
	 * 将xml格式的字符串转换成Map对象
	 * 
	 * @param xmlStr
	 *            xml格式的字符串
	 * @return Map对象
	 * @throws Exception
	 *             异常
	 */
	public static Map<String, Object> xmlStrToMap(String xmlStr)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		// 将xml格式的字符串转换成Document对象
		Document doc = DocumentHelper.parseText(xmlStr);
		// 获取根节点
		Element root = doc.getRootElement();
		// 获取根节点下的所有元素
		List children = root.elements();
		// 循环所有子元素
		if (children != null && children.size() > 0) {
			for (int i = 0; i < children.size(); i++) {
				Element child = (Element) children.get(i);
				map.put(child.getName(), child.getTextTrim());
				if (child.getName().equals("returnPoint")) {
					for (int j = 0; j < child.elements().size(); j++) {
						Element child1 = (Element) child.elements().get(j);
						map.put(child1.getName(), child1.getTextTrim());
					}
				}
			}
		}
		return map;
	}
	
	private static List<Element> getElement(Element node) {
	    List<Element> list = node.elements();
	    if (list.size() > 0) {
	      for (int i = 0; i < list.size(); i++) {
	        //获取task下的所有子节点
	        Element element = list.get(i);
	        //遍历每一个子节点
	        if (!element.isTextOnly()) {
	          String name = element.getName();
	          if ("ITEM".equalsIgnoreCase(name)) {
	            System.out.println("attrName:" + name);
	            break;
	          } else {
	            list = getElement(element);
	          }
	        }
	      }
	    }
	    return list;
	  }
	
	/**
	 * 由于计费侧提供的接口协议没变，只是地址调整，割接到3.0的本地网需要调用新的地址
	 * 集团电子发票API接口调整
	 * 获取判断使用的地址
	 * jf3_flag 刷新开关  配置为1则表示启用割接地市判断，配置为0则表示按现有的流程
	 * Jf3_jt_latn_id  割接地市配置项（多个地市用逗号分隔，如果配置项调整为888，则表示全部调用新地址）
	 * resultLanIdStr 区域编码
	 * private String MonthlyBillWUHANURL = ""; 旧武汉
	 * private String MonthlyBillHBURL = "";旧湖北
	 * private String MonthlyBillWHjf3 = "";计费武汉
	 * private String MonthlyBillHBjf3 = "";计费湖北
	 * type 1 标识对比84201 0 标识对比1001
	 */
	private String getURLForJf3(String resultLanIdStr,String IS_WUHAN) {
		String jf3_flag = userResourceConfigService.getValue("jf3_flag","");////增加刷新开关  ,配置为1则表示启用割接地市判断，配置为0则表示按现有的流程
		_log.info("配置文件读取参数:jf3_flag="+jf3_flag);
		String str;
		if("84201".equals(IS_WUHAN)) {
			str=userResourceConfigService.getValue("jf3_jt_latn_id","");
		}else {
			str=userResourceConfigService.getValue("jf3_latn_id","");
		}
		_log.info("配置文件读取参数:IS_WUHAN="+IS_WUHAN+";str="+str);
		if("1".equals(jf3_flag)) {
			if("888".equals(str)) {
				if(resultLanIdStr.equals(IS_WUHAN)) {
					return MonthlyBillWHjf3;
				}else {
					return MonthlyBillHBjf3;
				}
			}else {
				String[] split_jt_latn_id = str.split(",");
				for (String string : split_jt_latn_id) {
					if(string.equals(resultLanIdStr)) {
						//包含
						if(resultLanIdStr.equals(IS_WUHAN)) {
							return MonthlyBillWHjf3;
						}else {
							return MonthlyBillHBjf3;
						}
					}
				}
			}
			
		}
		if(resultLanIdStr.equals(IS_WUHAN)) {
			return MonthlyBillWUHANURL;
		}
		else {
			return MonthlyBillHBURL;
		}
	}
	private String getURLForJf4(String resultLanIdStr,String IS_WUHAN) {
		String jf3_flag = userResourceConfigService.getValue("jf3_flag","");////增加刷新开关  ,配置为1则表示启用割接地市判断，配置为0则表示按现有的流程
		_log.info("配置文件读取参数:jf3_flag="+jf3_flag);
		String str;
		if("84201".equals(IS_WUHAN)) {
			str=userResourceConfigService.getValue("jf3_jt_latn_id","");
		}else {
			str=userResourceConfigService.getValue("jf3_latn_id","");
		}
		_log.info("配置文件读取参数:IS_WUHAN="+IS_WUHAN+";str="+str);
		if("1".equals(jf3_flag)) {
			if("888".equals(str)) {
				return "1";
			}else {
				String[] split_jt_latn_id = str.split(",");
				for (String string : split_jt_latn_id) {
					if(string.equals(resultLanIdStr)) {
						//包含
						return "1";
					}
				}
			}
			
		}
		return "0";
	}
	/**
	 * 由于计费侧提供的接口协议没变，只是地址调整，割接到3.0的本地网需要调用新的地址
	 * 集团电子发票API接口调整
	 * 获取判断使用的地址
	 * jf3_flag 刷新开关  配置为1则表示启用割接地市判断，配置为0则表示按现有的流程
	 * Jf3_jt_latn_id  割接地市配置项（多个地市用逗号分隔，如果配置项调整为888，则表示全部调用新地址）
	 * resultLanIdStr 区域编码
	 * cityId
	 * jf3_jt_latn_id 是84201这种
		jf3_latn_id是1001 1018 这种
		jf3_area_coee是027 0716 这种
	 */
	private String getVersionType(String cityId,String type) {
		String jf3_flag = userResourceConfigService.getValue("jf3_flag","");////增加刷新开关  ,配置为1则表示启用割接地市判断，配置为0则表示按现有的流程
		String jf3_jt_latn_id = userResourceConfigService.getValue("jf3_jt_latn_id","");
		String jf3_latn_id = userResourceConfigService.getValue("jf3_latn_id","");
		String str;
		if("0".equals(type)) {
			//1001类型
			str = jf3_latn_id;
		}else {
			//84201 类型
			str = jf3_jt_latn_id;
		}
		//1 新流程  0 旧的流程
		if("1".equals(jf3_flag)) {
			if("888".equals(str)) {
				return "1";//新的
			}else {
				String[] split_jt_latn_id = str.split(",");
				for (String string : split_jt_latn_id) {
					if(string.equals(cityId)) {
						//包含,仅区分新旧
						return "1";//新的 Recharged.jf3@027.ctnbc-bon.net
					}
				}
			}
			
		}
		return "0";//旧的 SeverRecharge.SGWPAY@027.ctnbc-bon.net  
	}
	
	/**
	 * @TODO
	 * 新的橙分期接口OrangeStageBill.jf3入参Area_Code为区号(027,0716这种)，但是用户鉴权的HomeAreaCode为1001,1016这种，所以需要做一个映射转换
	 */
	private String getAreaCode(String homeAreaCode) {
		String [][]  arr1= {{"1001","027"},{"1003","0710"},{"1004","0713"},{"1005","0717"},{"1006","0712"},
				{"1007","0711"},{"1008","0715"},{"1009","0719"},{"1010","0724"},{"1011","0714"},{"1012","0722"},
				{"1013","0718"},{"1014","0728"},{"1015","0728"},{"1016","0728"},{"1017","0719"},{"1018","0716"}};
		for (String[] strings : arr1) {
			if(homeAreaCode.equals(strings[0])) {
				return strings[1];
			}
		}
		return "027";
	}
	
	/**
	 * 调试用
	 * @TODO
	 *
	 */
	private static String getURLForJf32(String resultLanIdStr) {
		String jf3_flag="1";
		String Jf3_jt_latn_id="84201,84210";
		String IS_WUHAN="84201";
		String MonthlyBillWHjf3="1";
		String MonthlyBillHBjf3="2";
		String MonthlyBillWUHANURL="3";
		String MonthlyBillHBURL="4";
		
		if("1".equals(jf3_flag)) {
			if("888".equals(Jf3_jt_latn_id)) {
				if(resultLanIdStr.equals(IS_WUHAN)) {
					return MonthlyBillWHjf3;
				}else {
					return MonthlyBillHBjf3;
				}
			}else {
				String[] split_jt_latn_id = Jf3_jt_latn_id.split(",");
				for (String string : split_jt_latn_id) {
					if(string.equals(resultLanIdStr)) {
						//包含
						if(resultLanIdStr.equals(IS_WUHAN)) {
							return MonthlyBillWHjf3;
						}else {
							return MonthlyBillHBjf3;
						}
					}
				}
			}
			
		}
		if(resultLanIdStr.equals(IS_WUHAN)) {
			return MonthlyBillWUHANURL;
		}
		else {
			return MonthlyBillHBURL;
		}
	}
	
}
